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; }
}
编译器会抱怨:结构VS类实现一个接口
无法隐式转换类型 'System.Collections.Generic.List <Tests.Program.FooStruct>' 到“System.Collections.Generic。 IEnumerable <Tests.Program.IFoo>'。存在明确的转换(您是否缺少演员?)
为什么?
为什么类和结构之间有区别? 任何解决方法?
看到如此质疑http://stackoverflow.com/questions/13049/whats-the-difference-between-struct-and-class-in-net 而接受的答案:http://stackoverflow.com/a/13275/1155847 –
也在这里:http://stackoverflow.com/questions/9688268/why-cannot-ienumerablestruct-be-cast-as-ienumerableobject –
只是一个小事情关于术语:接口是“实现的”,而不是“继承的”。 –