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


当前回答

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

对于字符串

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

对于编号

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

其他回答

无LINQ重复:

float[] floats = System.Array.ConvertAll(new float[16], v => 1.0f);
var contacts = new[]
{
    new 
    {
        Name = " Eugene Zabokritski",
        PhoneNumbers = new[] { "206-555-0108", "425-555-0001" }
    },
    new 
    {
        Name = " Hanying Feng",
        PhoneNumbers = new[] { "650-555-0199" }
    }
};

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

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 array = Enumerable.Repeat(string.Empty, 37).ToArray();

也请参加本次讨论。

创建和初始化对象数组的另一种方法。这与上面@Amol发布的示例类似,只是这一个使用了构造函数。一点点多态性洒了进来,我无法抗拒。

IUser[] userArray = new IUser[]
{
    new DummyUser("abc@cde.edu", "Gibberish"),
    new SmartyUser("pga@lna.it", "Italian", "Engineer")
};

上下文类:

interface IUser
{
    string EMail { get; }       // immutable, so get only an no set
    string Language { get; }
}

public class DummyUser : IUser
{
    public DummyUser(string email, string language)
    {
        m_email = email;
        m_language = language;
    }

    private string m_email;
    public string EMail
    {
        get { return m_email; }
    }

    private string m_language;
    public string Language
    {
        get { return m_language; }
    }
}

public class SmartyUser : IUser
{
    public SmartyUser(string email, string language, string occupation)
    {
        m_email = email;
        m_language = language;
        m_occupation = occupation;
    }

    private string m_email;
    public string EMail
    {
        get { return m_email; }
    }

    private string m_language;
    public string Language
    {
        get { return m_language; }
    }

    private string m_occupation;
}