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

其他回答

另一种方法是调用静态函数(用于静态对象)或实例对象的任何函数。这可用于成员初始化。

现在我还没有测试所有这些,所以我将把我测试过的(静态成员和静态函数)

Class x {
    private static Option[] options = GetOptionList();
    private static Option[] GetOptionList() {

        return (someSourceOfData).Select(dataitem => new Option()
                 {field=dataitem.value,field2=dataitem.othervalue});
    }
}

我想知道的是,是否有绕过函数声明的方法。我知道在这个例子中,它可以直接使用,但假设函数稍微复杂一些,不能简化为一个表达式。

我想象如下(但不起作用)

Class x {
    private static Option[] options = () => {
        Lots of prep stuff here that means we can not just use the next line
        return (someSourceOfData).Select(dataitem => new Option()
                 {field=dataitem.value,field2=dataitem.othervalue});
    }
}

基本上是为填充变量的范围声明函数的一种方式。如果有人能教我怎么做,我会很高兴的。

对于以下类别:

public class Page
{

    private string data;

    public Page()
    {
    }

    public Page(string data)
    {
        this.Data = data;
    }

    public string Data
    {
        get
        {
            return this.data;
        }
        set
        {
            this.data = value;
        }
    }
}

您可以按如下方式初始化上述对象的数组。

Pages = new Page[] { new Page("a string") };

希望这有帮助。

Enumerable.Repeat(String.Empty, count).ToArray()

将创建重复“count”次的空字符串数组。若您希望使用相同但特殊的默认元素值初始化数组。注意引用类型,所有元素都将引用同一对象。

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