private static void TestStructInterface()
{
IFoo foo1 = new FooClass(); // works
IFoo foo2 = new FooStruct(); // works
IEnumerable<IFoo> foos1 = new List<FooClass>(); // works
IEnumerable<IFoo> foos2 = new List<FooStruct>(); // compiler error
}
interface IFoo
{
string Thing { get; set; }
}
class FooClass : IFoo
{
public string Thing { get; set; }
}
struct FooStruct : IFoo
{
public string Thing { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
编译器抱怨:
无法将类型'System.Collections.Generic.List <Tests.Program.FooStruct>'隐式转换为'System.Collections.Generic.IEnumerable <Tests.Program.IFoo>'.存在显式转换(您是否错过了演员?)
为什么?
为什么类和结构之间有区别?任何解决方法?
就像 Bharathram Attiyannan 回答的那样,值类型根本不支持方差。
解决方法很简单:
List<FooStruct> listOfFooStruct = new List<FooStruct>();
IEnumerable<IFoo> enumerableOfFoo = listOfFooStruct.Cast<IFoo>();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
396 次 |
| 最近记录: |