C# 分配给IList时数组的协变行为<;T>;
我想知道一个数组如何与实现IList的C# 分配给IList时数组的协变行为<;T>;,c#,arrays,covariance,ilist,C#,Arrays,Covariance,Ilist,我想知道一个数组如何与实现IList的List有不同的行为,当分配给IList时,数组似乎绕过了IList的非协变性质(它没有定义为IList)。 在下面的示例中,除“people3”外,所有作业都正常。为什么任务在personArray的“people4”情况下有效 public interface IPerson { } public class Person : IPerson { } var personList = new List<Person>(); var pers
List
有不同的行为,当分配给IList
时,数组似乎绕过了IList的非协变性质(它没有定义为IList
)。
在下面的示例中,除“people3”外,所有作业都正常。为什么任务在personArray的“people4”情况下有效
public interface IPerson { }
public class Person : IPerson { }
var personList = new List<Person>();
var personArray = new Person[0];
IList<Person> people1 = personList;
IList<Person> people2 = personArray;
IList<IPerson> people3 = personList;
IList<IPerson> people4 = personArray;
公共接口IPerson{}
公共类人士:IPerson{}
var personList=新列表();
var personArray=新用户[0];
IList people1=个人主义者;
IList people2=人物;
IList people3=个人主义者;
IList people4=人物;
如果T:U
,则可以将T[]
的实例强制转换为IList
,但即使IList.IsReadOnly
将为false,IList.IsReadOnly
将返回true
。请注意,即使IList.IsReadOnly
返回true
,如果正在写入的特定项恰好满足类型T
,尝试写入IList
仍可能成功。据我所知,无法确定由U
标识的特定实例是否可以存储到ILIst
中,除非尝试它并观察是否发生异常。这是因为这种协方差是一件坏事,而C#只支持数组,因为Java支持它
这会导致运行时错误
object[] myArray = new string[1];
myArray[0] = 1;
List<object> myList = new List<string>(1);
myList[0] = 1;
这会导致编译时错误
object[] myArray = new string[1];
myArray[0] = 1;
List<object> myList = new List<string>(1);
myList[0] = 1;
List myList=新列表(1);
myList[0]=1;
所以我不会重提它。不知何故,我试图寻找相关问题时,却忽略了其中的一个解释……那么,您是否认为纯粹因为可能的运行时分配错误,这是一件“坏事”?否则,我喜欢兼容子类/基类的自由行为。如果您打算将其作为一个列表,那么您本来应该这样做。通过将其转换为列表,您可以将除个人以外的其他内容添加到列表中。在编译时使用列表和运行时使用数组都可以防止这种情况。实际上,您并没有更多的灵活性。在这种情况下,我现在倾向于使用List、IReadOnlyList、IReadOnlyCollection.:)