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


当前回答

对于C#声明中的多维数组,请赋值。

public class Program
{
    static void Main()
    {
        char[][] charArr = new char[][] { new char[] { 'a', 'b' }, new char[] { 'c', 'd' } };

        int[][] intArr = new int[][] { new int[] { 1, 2 }, new int[] { 3, 4 } };
    }

}

其他回答

带有表达式的平凡解决方案。注意,使用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
var contacts = new[]
{
    new 
    {
        Name = " Eugene Zabokritski",
        PhoneNumbers = new[] { "206-555-0108", "425-555-0001" }
    },
    new 
    {
        Name = " Hanying Feng",
        PhoneNumbers = new[] { "650-555-0199" }
    }
};

对于C#声明中的多维数组,请赋值。

public class Program
{
    static void Main()
    {
        char[][] charArr = new char[][] { new char[] { 'a', 'b' }, new char[] { 'c', 'd' } };

        int[][] intArr = new int[][] { new int[] { 1, 2 }, new int[] { 3, 4 } };
    }

}
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)"

hi只是为了添加另一种方式:从此页面:https://learn.microsoft.com/it-it/dotnet/api/system.linq.enumerable.range?view=netcore-3.1

如果您想生成0到9的指定范围内的整数序列,可以使用此表单:

using System.Linq
.....
public int[] arrayName = Enumerable.Range(0, 9).ToArray();