2012-12-28 107 views
20

Possible Duplicate:
Declare a Const ArrayConst字符串陣列

我需要類中的一個常量字符串數組。喜歡的東西

public class some_class_t 
{ 
    public const string[] names = new string[4] 
    { 
     "alpha", "beta", "gamma", "delta" 
    }; 
} 

但這種代碼導致錯誤:

A constant 'names' of reference type 'string[]' can only be initialized with null.

我該怎麼辦?

+1

數組是可變的。除非它們爲零,否則它們不能保持不變。 –

+0

聲明爲'readonly' –

回答

57

聲明爲readonly,而不是const

public readonly string[] names = { "alpha", "beta", "gamma", "delta" }; 
+0

更多詳細信息請參見[http://stackoverflow.com/a/5142378/1080355](http://stackoverflow.com/a/5142378/1080355) – VSB

+2

並聲明它是靜態的,所以我將使用公共只讀string [] names = {「alpha」,「beta」,「gamma」,「delta」}; –