C#可以使用哪些数组初始化语法?


当前回答

带有表达式的平凡解决方案。注意,使用NewArrayInit,您可以只创建一维数组。

NewArrayExpression expr = Expression.NewArrayInit(typeof(int), new[] { Expression.Constant(2), Expression.Constant(3) });
int[] array = Expression.Lambda<Func<int[]>>(expr).Compile()(); // compile and call callback

其他回答

只是一张纸条

以下阵列:

string[] array = new string[2];
string[] array2 = new string[] { "A", "B" };
string[] array3 = { "A" , "B" };
string[] array4 = new[] { "A", "B" };

将编译为:

string[] array = new string[2];
string[] array2 = new string[] { "A", "B" };
string[] array3 = new string[] { "A", "B" };
string[] array4 = new string[] { "A", "B" };

非空数组

var data0=新int[3]var data1=新int[3]{1,2,3}var data2=新int[]{1,2,3}var data3=新[]{1,2,3}var data4={1,2,3}不可编译。请改用int[]data5={1,2,3}。

空数组

var data6=新int[0]var data7=新int[]{}vardata8=new[]{}和int[]data9=new[]}不可编译。var data10={}不可编译。请改用int[]data11={}。

作为方法的参数

只有可以指定var关键字的表达式才能作为参数传递。

Foo(新int[2])Foo(新int[2]{1,2})Foo(新int[]{1,2})Foo(新[]{1,2})Foo({1,2})不可编译Foo(新int[0])Foo(新int[]{})Foo({})不可编译

要初始化空数组,在dotnet 5.0中应该是array.empty<T>()

对于字符串

var items = Array.Empty<string>();

对于编号

var items = Array.Empty<int>();
int[] array = new int[4]; 
array[0] = 10;
array[1] = 20;
array[2] = 30;

or

string[] week = new string[] {"Sunday","Monday","Tuesday"};

or

string[] array = { "Sunday" , "Monday" };

并且在多维阵列中

    Dim i, j As Integer
    Dim strArr(1, 2) As String

    strArr(0, 0) = "First (0,0)"
    strArr(0, 1) = "Second (0,1)"

    strArr(1, 0) = "Third (1,0)"
    strArr(1, 1) = "Fourth (1,1)"

创建自定义类数组的示例

下面是类定义。

public class DummyUser
{
    public string email { get; set; }
    public string language { get; set; }
}

这是初始化数组的方法:

private DummyUser[] arrDummyUser = new DummyUser[]
{
    new DummyUser{
       email = "abc.xyz@email.com",
       language = "English"
    },
    new DummyUser{
       email = "def@email.com",
       language = "Spanish"
    }
};