从类外部初始化公共类成员数组

dan*_*jar 1 .net c# arrays

我想,我想做的事情是非常基本的.代码示例清楚地显示了它.

class MyClass{
     public string[] Bar;
}

MyClass Foo = new MyClass();
Foo.Bar = { "word", "word", "word" };
Run Code Online (Sandbox Code Playgroud)

此代码在Visual Studio C#中给出了一个错误.(只能使用赋值,调用,递增,递减和新对象表达式作为语句)

有没有更好的方法为类提供数组?阵列可能是const我的一部分.

如何从外部向类提供(const)数组?

我不想使用构造函数,因为数组应该是可选的.

Jon*_*eet 5

您只能使用{} 不带new运算符作为声明的一部分来初始化数组(这反过来必须明确指定数组类型).这与它是否在同一个班级无关:

int[] x = { 1, 2, 3 }; // Fine
x = { 4, 5, 6 }; // Fail
x = new[] { 7, 8, 9 }; // Implicitly typed array as of C# 3
x = new int[] { 10, 11, 12 }; // Works with all versions of C#
Run Code Online (Sandbox Code Playgroud)

有关详细信息,请参阅C#4规范的12.6节(数组初始值设定项),10.5(字段声明),8.5.1(局部变量声明)和7.6.10.4(数组创建表达式).

回答你对Darin帖子的评论:不,在任何意义上都没有"const"数组,我可以想象你的意思.即使你使数组变量只读,如下所示:

private static readonly int[] Values = { 1, 2, 3 };
Run Code Online (Sandbox Code Playgroud)

只使变量只读.Values将始终引用相同的数组对象(因此将始终具有3个元素),但数组本身始终是可变的.如果你想构建一个只读集合,我建议使用ReadOnlyCollection<T>,可能通过List.AsReadOnly():

private static readonly ReadOnlyCollection<int> Values =
    new List<int> { 1, 2, 3 }.AsReadOnly();
Run Code Online (Sandbox Code Playgroud)