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


当前回答

只是一张纸条

以下阵列:

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

其他回答

无LINQ重复:

float[] floats = System.Array.ConvertAll(new float[16], v => 1.0f);

如果您想初始化一个预先初始化的相等(非空或非默认)元素的固定数组,请使用以下命令:

var array = Enumerable.Repeat(string.Empty, 37).ToArray();

也请参加本次讨论。

您还可以创建动态数组,即,在创建数组之前,您可以先向用户询问数组的大小。

Console.Write("Enter size of array");
int n = Convert.ToInt16(Console.ReadLine());

int[] dynamicSizedArray= new int[n]; // Here we have created an array of size n
Console.WriteLine("Input Elements");
for(int i=0;i<n;i++)
{
     dynamicSizedArray[i] = Convert.ToInt32(Console.ReadLine());
}

Console.WriteLine("Elements of array are :");
foreach (int i in dynamicSizedArray)
{
    Console.WriteLine(i);
}
Console.ReadKey();
var contacts = new[]
{
    new 
    {
        Name = " Eugene Zabokritski",
        PhoneNumbers = new[] { "206-555-0108", "425-555-0001" }
    },
    new 
    {
        Name = " Hanying Feng",
        PhoneNumbers = new[] { "650-555-0199" }
    }
};

创建自定义类数组的示例

下面是类定义。

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