C#编译时类型转换错误
这段代码出现编译时类型转换错误。。。不知道我是否只是累了,但我不知道我需要在课堂上改变什么来解决这个问题。任何指点都会很棒的,谢谢 错误为:“错误CS0266:无法将类型C#编译时类型转换错误,c#,C#,这段代码出现编译时类型转换错误。。。不知道我是否只是累了,但我不知道我需要在课堂上改变什么来解决这个问题。任何指点都会很棒的,谢谢 错误为:“错误CS0266:无法将类型csharpfinal.Packaging隐式转换为csharpfinal.IGetValue。存在显式转换(是否缺少强制转换?) 接口ISetValue { 无效设置数据(T数据); } 接口IGetValue { T GetData(); } 类包装:ISetValue、IGetValue { 私人T-storedData;
csharpfinal.Packaging
隐式转换为csharpfinal.IGetValue
。存在显式转换(是否缺少强制转换?)
接口ISetValue
{
无效设置数据(T数据);
}
接口IGetValue
{
T GetData();
}
类包装:ISetValue、IGetValue
{
私人T-storedData;
无效ISetValue.SetData(T数据)
{
this.storedData=数据;
}
T IGetValue.GetData()
{
返回此.storedData;
}
}
班级计划
{
静态void Main(字符串[]参数)
{
包装stringPackage=新包装();
ISetValue setStringValue=stringPackage;
setStringValue.SetData(“示例字符串”);
//下面的行导致编译时错误
IGetValue getObjectValue=stringPackage;
WriteLine(“{0}”,getObjectValue.GetData());
}
}
接口ISetValue
{
无效设置数据(T数据);
}
接口IGetValue
{
T GetData();
}
类包装:ISetValue、IGetValue
{
私人T-storedData;
无效ISetValue.SetData(T数据)
{
this.storedData=数据;
}
T IGetValue.GetData()
{
返回此.storedData;
}
}
班级计划
{
静态void Main(字符串[]参数)
{
包装stringPackage=新包装();
ISetValue setStringValue=stringPackage;
setStringValue.SetData(“示例字符串”);
//下面的行导致编译时错误
IGetValue getObjectValue=stringPackage;
WriteLine(“{0}”,getObjectValue.GetData());
}
}
更多信息:修改此代码
interface ISetValue<T>
{
void SetData(T data);
}
interface IGetValue<T>
{
T GetData();
}
接口ISetValue
{
无效设置数据(T数据);
}
接口IGetValue
{
T GetData();
}
到
接口ISetValue
{
无效设置数据(T数据);
}
接口IGetValue
{
T GetData();
}
对于泛型类型参数,out关键字指定
参数是协变的。您可以在泛型中使用out关键字
接口和委托
协方差使您能够使用更派生的
类型,而不是泛型参数指定的类型。这就允许
隐式转换实现变量接口和
委托类型的隐式转换。协变与逆变
引用类型支持,但引用类型不支持
值类型
但是您试图将对象
泛型转换为字符串
泛型,这就是为什么会出现编译时错误
您可以将对象初始化的常规类型更改为对象
,以修复它:
Packaging<object> stringPackage = new Packaging<object>();
ISetValue<object> setStringValue = stringPackage;
Packaging stringPackage=new Packaging();
ISetValue setStringValue=stringPackage;
IGetValue
应该这样吗
IGetValue
您是否尝试过IGetValue getObjectValue=stringPackage
我的代码是错的吗?我试图在不改变的情况下做这件事,这不是ISetValue
?我的错,只是从IGetValue复制粘贴了它:D,谢谢,我不确定,这就是我问的原因;是的,我试着在不改变的情况下做这件事,应该更清楚。谢谢
interface ISetValue<T>
{
void SetData(T data);
}
interface IGetValue<T>
{
T GetData();
}
interface ISetValue<in T>
{
void SetData(T data);
}
interface IGetValue<out T>
{
T GetData();
}
Packaging<string> stringPackage = new Packaging<string>();
IGetValue<object> getObjectValue = stringPackage;
Packaging<object> stringPackage = new Packaging<object>();
ISetValue<object> setStringValue = stringPackage;
IGetValue<object>
IGetValue<string>