IEnumerable<T>是共变体,但它不支持值类型,仅支持引用类型.以下简单代码编译成功:
IEnumerable<string> strList = new List<string>();
IEnumerable<object> objList = strList;
Run Code Online (Sandbox Code Playgroud)
但是从更改string到int将得到编译错误:
IEnumerable<int> intList = new List<int>();
IEnumerable<object> objList = intList;
Run Code Online (Sandbox Code Playgroud)
原因在MSDN中解释:
差异仅适用于参考类型; 如果为变量类型参数指定值类型,则该类型参数对于生成的构造类型是不变的.
我搜索过并发现有些问题提到的原因是值类型和引用类型之间的装箱.但它仍然不清楚我的想法为什么拳击是什么原因?
有人可以给出一个简单而详细的解释为什么协方差和逆变不支持值类型以及拳击如何影响这个?
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>'.存在显式转换(您是否错过了演员?)
为什么?
为什么类和结构之间有区别?任何解决方法?