列表,数组和IEnumerable协方差

Lev*_*lho 6 c# arrays ienumerable list covariance

我将从几个假设开始,以更好地解释我的问题的背景:

数组协方差

假设1.1

值类型的数组不是协变的.int[]无法通过object[].

假设1.2

引用类型的数组与有效的协变IEnumerable.string[]可以通过IEnumerable<object>).

假设1.3

引用类型的数组与有效的协变数组协变.string[]可以通过object[].

列出协方差

假设2.1(与1.1相同)

值类型的列表不是协变的.List<int>无法通过List<object>.

假设2.2(与1.2相同)

引用类型的列表与有效的协变IEnumerable.List<string>可以通过IEnumerable<object>).

假设2.3(与1.3不同)

引用类型列表与有效协变不一致List.List<string>不能通过List<object>).


我的问题涉及假设1.3,2.2和2.3.特别:

  1. 为什么可以string[]通过object[],但List<string>不是为了List<object>
  2. 为什么可以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>.

  • 是的,他们允许阵列协方差是最令人讨厌的.他们不应该. (2认同)