gpt4 book ai didi

c# - 为什么 C# 在两个 int 数组语法上表现不同

转载 作者:IT王子 更新时间:2023-10-29 03:42:13 26 4
gpt4 key购买 nike

C# 中的数组在引用类型上隐式协变:

object[] listString = new string[] { "string1", "string2" };

但不是值类型,所以如果你把string改成int,你会得到编译错误:

object[] listInt = new int[] {0, 1}; // compile error

现在,问题是当你像下面的两种语法一样声明 int 数组时,它们没有显式声明 int 类型,只是在 new[] 上进行区分,编译器会区别对待:

object[] list1 = { 0, 1 };       //compile successfully
object[] list2 = new[] {0, 1}; //compile error

你会得到 object[] list1 = { 0, 1 }; 编译成功,但是 object[] list2= new[] {0, 1}; 编译错误。

似乎 C# 编译器对待

object[] list1 = { 0, 1 };

作为

object[] list1 = new object[]{ 0, 1 };

但是

object[] list2 = new[] { 0, 1 };

作为

object[] list2 = new int[]{ 0, 1 };  //error because of co-variant

为什么 C# 编译器在这种情况下表现不同?

最佳答案

编译版本使用数组初始化程序 来初始化list1。 C# 语言规范,§1.110(“数组初始值设定项”)指出:

An array initializer consists of a sequence of variable initializers, enclosed by “{”and “}” tokens and separated by “,” tokens. Each variable initializer is an expression or, in the case of a multi-dimensional array, a nested array initializer.

The context in which an array initializer is used determines the type of the array being initialized. In an array creation expression, the array type immediately precedes the initializer, or is inferred from the expressions in the array initializer. In a field or variable declaration, the array type is the type of the field or variable being declared.

When an array initializer is used in a field or variable declaration, such as:

int[] a = {0, 2, 4, 6, 8};

it is simply shorthand for an equivalent array creation expression:

int[] a = new int[] {0, 2, 4, 6, 8};

所以很明显这应该编译。

第二个版本使用显式数组创建表达式,您可以在其中明确指示编译器要创建什么类型的数组。 §1.51.10.4(“数组创建表达式”)指出:

An array creation expression of the third form is referred to as an implicitly typed array creation expression. It is similar to the second form, except that the element type of the array is not explicitly given, but determined as the best common type (§1.50.2.14) of the set of expressions in the array initializer.

因此,第二个版本等同于

object[] list2 = new int[] { 0, 1 };

所以现在的问题实际上变成了“为什么我不能将 int[] 分配给 object[]”,就像您在问题末尾提到的那样.答案也很简单,在§1.109(“数组协方差”)中给出:

Array covariance specifically does not extend to arrays of value-types. For example, no conversion exists that permits an int[] to be treated as an object[].

关于c# - 为什么 C# 在两个 int 数组语法上表现不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16457147/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com