Lev*_*lho 6 c# arrays ienumerable list covariance
我将从几个假设开始,以更好地解释我的问题的背景:
值类型的数组不是协变的.int[]无法通过object[].
引用类型的数组与有效的协变IEnumerable.string[]可以通过IEnumerable<object>).
引用类型的数组与有效的协变数组协变.string[]可以通过object[].
值类型的列表不是协变的.List<int>无法通过List<object>.
引用类型的列表与有效的协变IEnumerable.List<string>可以通过IEnumerable<object>).
引用类型列表与有效协变不一致List.List<string>不能通过List<object>).
我的问题涉及假设1.3,2.2和2.3.特别:
string[]通过object[],但List<string>不是为了List<object>?List<string>通过IEnumerable<object>而不是为了List<object>?Lee*_*Lee 13
列表协方差是不安全的:
List<string> strings = new List<string> { "a", "b", "c" };
List<object> objects = strings;
objects.Add(1); //
Run Code Online (Sandbox Code Playgroud)
由于同样的原因,数组协方差也是不安全的:
string[] strings = new[] { "a", "b", "c" };
object[] objects = strings;
objects[0] = 1; //throws ArrayTypeMismatchException
Run Code Online (Sandbox Code Playgroud)
C#中的数组协方差被认为是一个错误,并且从版本1开始就存在.
由于收集无法通过修改IEnumerable<T>界面,它是安全的键入List<string>作为IEnumerable<object>.