考虑:IEnumerable <IMyInterface>隐式地从类[]但不是来自Struct []。为什么?
public interface IMyInterface{
}
public class MyClass:IMyInterface{
public MyClass(){}
}
public struct MyStruct:IMyInterface{
private int _myField;
public MyStruct(int myField){_myField = myField;}
}
我为什么可以这样写:
IEnumerable<IMyInterface> myClassImps = new[] {
new MyClass(),
new MyClass(),
new MyClass()
};
但不是:
IEnumerable<IMyInterface> myStructImps = new[]{
new MyStruct(0),
new MyStruct(1),
new MyStruct(2)
};
这给了我以下警告:
错误29无法隐式转换键入'MyApp.MyNS.MyStruct []'到'System.Co llections.Generic.IEnumerable <MyApp.MyNS.IMyInterface>'
,而必须写成:
IEnumerable<IMyInterface> myStructImps = new IMyInterface[]{
new MyStruct(0),
new MyStruct(1),
new MyStruct(2)
};
这个问题用C#3.0标记,所以你说什么差异? – 2011-04-28 21:43:00
@Darin对不起错误的引用 – 2011-04-28 21:52:34
了解我确实看到我的答案中存在空白,但我不明白这个解释的一件事是,如果这实际上只是一个协变问题,那他为什么要实例化赋值enumerable用'MyClass'的数组,但不包含'MyStruct'的数组。这尤其是为什么我认为这与拳击有关。 – LJM 2011-04-29 02:56:57