没有关键字“”的数组初始化;新的”;

本文关键字:初始化 新的 数组 关键字 | 更新日期: 2023-09-27 18:25:51

在C#中,可以在不使用关键字"new"的情况下初始化数组,如以下示例所示:

int[] x = { 10, 20, 30 };

这是否意味着数组将在堆栈上初始化,因为关键字"new"是初始化堆上某些东西所必需的?

没有关键字“”的数组初始化;新的”;

简短回答:不。

您显示的代码是int[] x = new [] { 10, 20, 30 }
的简写是int[] x = new int[] { 10, 20, 30}
的简写是int[] x = new int[3]; x[0] = 10; x[1] = 20; x[2] = 30; 的简写

(请参阅MSDN)

在执行方面没有区别。

在堆栈上分配数组的唯一方法是使用带有stackalloc关键字的不安全代码,如注释中所述。MSDN示例:

int* block = stackalloc int[100];

我想在这里添加更多内容。

堆栈中的内容是int数组的heapAddress。允许比如,当你把数组传递到某个函数中时正在传递的是来自Stack的heapAddress值。

生成的中间代码对于new和没有new初始化都是相同的。

样本代码:

 public class Class1
{
    int[] a = new int[4];
}
public class Class2
{
    int[] a = { 1, 2, 3, 4 };
}

编译:

(由于我没有上传图像所需的点,您可以在ildasm中查看它)