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


当前回答

var contacts = new[]
{
    new 
    {
        Name = " Eugene Zabokritski",
        PhoneNumbers = new[] { "206-555-0108", "425-555-0001" }
    },
    new 
    {
        Name = " Hanying Feng",
        PhoneNumbers = new[] { "650-555-0199" }
    }
};

其他回答

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

这些是简单数组的当前声明和初始化方法。

string[] array = new string[2]; // creates array of length 2, default values
string[] array = new string[] { "A", "B" }; // creates populated array of length 2
string[] array = { "A" , "B" }; // creates populated array of length 2
string[] array = new[] { "A", "B" }; // created populated array of length 2

注意,还有其他获取数组的技术,例如IEnumerable<T>上的Linq ToArray()扩展。

还要注意,在上面的声明中,前两个可以用var(C#3+)替换左边的字符串[],因为右边的信息足以推断正确的类型。第三行必须按照显示的方式编写,因为仅使用数组初始化语法不足以满足编译器的要求。第四个也可以使用推理。因此,如果你关注整个简短的事情,上面的内容可以写成

var array = new string[2]; // creates array of length 2, default values
var array = new string[] { "A", "B" }; // creates populated array of length 2
string[] array = { "A" , "B" }; // creates populated array of length 2
var array = new[] { "A", "B" }; // created populated array of length 2 

创建自定义类数组的示例

下面是类定义。

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

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();

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

对于字符串

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

对于编号

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