![](/img/trans.png)
[英]Public Read-Only array data Member - Update outside of class Constructor
[英]Initialize public Class Member Array from outside the Class
我想我真正想做的是基本的。 要編寫代碼的示例將其清楚地顯示出來。
class MyClass{
public string[] Bar;
}
MyClass Foo = new MyClass();
Foo.Bar = { "word", "word", "word" };
這段代碼給我Visual Studio C#中的錯誤。 (僅賦值,調用,遞增,遞減和新對象表達式可以用作語句)
有沒有更好的方法為該類提供數組? 就我而言,該數組可以是const
。
如何從外部為類提供一個(常量)數組?
我不想使用構造函數,因為該數組應該是可選的。
您只能使用{}
初始化數組, 而不能將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#
有關詳細信息,請參見C#4規范的第12.6節(數組初始化器),10.5節(字段聲明),8.5.1節(局部變量聲明)和7.6.10.4節(數組創建表達式)。
要回答您對Darin帖子的評論:不,從我能想象到的意義上講,沒有“ const”數組之類的東西。 即使將數組變量設置為只讀,也是如此:
private static readonly int[] Values = { 1, 2, 3 };
這只會使變量為只讀。 Values
將始終引用同一數組對象(因此將始終具有3個元素),但數組本身始終是可變的。 如果您想建立一個只讀集合,建議使用ReadOnlyCollection<T>
,可能是通過List.AsReadOnly() :
private static readonly ReadOnlyCollection<int> Values =
new List<int> { 1, 2, 3 }.AsReadOnly();
正確的數組初始化器語法為:
Foo.Bar = new[] { "word", "word", "word" };
僅當您在左側明確指定類型時,才能使用{ "word", "word", "word" }
:
string[] foo = { "word", "word", "word" };
您應該創建數組,也可以在Foo創建中進行以下初始化:
MyClass Foo = new MyClass{Bar = new []{ "word", "word", "word" }};
如果只想初始化一次數組,則將其定義為只讀,然后在構造函數中進行初始化:
class MyClass{
public readonly string[] Bar;
public MyClass(string[] bar)
{
Bar = bar;
}
}
MyClass Foo = new MyClass (new[] { "word", "word", "word" } );
編輯:如果您不喜歡在構造函數中對其進行初始化,則可以使用類似Single Singleton的模式:
class MyClass
{
private static string[] bar;
public static string[] Bar
{
get { return bar; }
set
{
if (bar == null)
bar = value;
}
}
}
但是,如果添加lock
語句,它將是線程安全的,但可能會降低性能。
在方括號之前添加new []:
Foo.Bar = new[] { "word", "word", "word" };
除了聲明之外,您無法創建const數組並對其進行初始化。 您可以創建一個readonly
數組,該數組可以在構造函數中初始化。 如果要在其他地方設置數組的值,則它必須是一個普通的數據字段。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.