<分区>
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; }
}
编译器提示:
Cannot implicitly convert type 'System.Collections.Generic.List<Tests.Program.FooStruct>' to 'System.Collections.Generic.IEnumerable<Tests.Program.IFoo>'. An explicit conversion exists (are you missing a cast?)
为什么?
为什么类和结构之间存在差异?
有什么解决方法吗?