2012-04-13 91 views
6

this question,我知道一個const string可以是const事物的串聯。現在,枚舉只是一個整數集合,不是嗎? 那麼,爲什麼是不是確定要做到這一點:如何在常量字符串中包含枚舉值?

const string blah = "blah " + MyEnum.Value1; 

或本:

const string bloh = "bloh " + (int)MyEnum.Value1; 

你會怎麼包括一個常量字符串的枚舉值?

現實生活中的示例:在構建SQL查詢時,我想要有"where status <> " + StatusEnum.Discarded

+2

至於爲什麼一個猜測:串聯整數可能涉及文化相關性問題。你的'int.ToString()'可能與我的'int.ToString()'不一樣。也許。只是一個猜測。特別是負數,也許。 – 2012-04-13 09:47:39

+0

哦,對,我沒有讀過我非常仔細地鏈接的問題。所以它不僅僅是關於枚舉,實際上也不可能在const字符串中包含const整數。 – Zonko 2012-04-13 09:55:44

+1

是的; 'const string foo =「abc」+ 1;'同樣失敗 – 2012-04-13 09:59:00

回答

6

作爲解決方法,你可以使用一個字段初始值,而不是一個常量,即

static readonly string blah = "blah " + MyEnum.Value1; 

static readonly string bloh = "bloh " + (int)MyEnum.Value1; 

至於爲什麼:爲枚舉情況下,枚舉格式實際上是相當複雜的,尤其是對[Flags]的情況,所以將它留給運行時是有意義的。對於int的情況,這仍然可能會受到文化特定問題的影響,因此需要延遲到運行時間。什麼編譯器實際上生成是操作這裏,即使用string.Concat(object,object)過載,等同於:

static readonly string blah = string.Concat("blah ", MyEnum.Value1); 
static readonly string bloh = string.Concat("bloh ", (int)MyEnum.Value1); 

其中string.Concat將執行.ToString()。因此,它可以說,下面會更有效(避免箱體和虛擬呼叫):

static readonly string blah = "blah " + MyEnum.Value1.ToString(); 
static readonly string bloh = "bloh " + ((int)MyEnum.Value1).ToString(); 

它將使用string.Concat(string,string)

+0

+1對於很好的解釋 – ABH 2012-04-13 09:59:05

4

您需要使用readonlystatic readonly而不是const

static readonly string blah = "blah " + MyEnum.Value1; 

MyEnum.Value1沒有作爲const處理的原因是,一個方法調用需要將值轉換爲字符串,並且一個方法調用的結果不被視爲恆定的值,即使該方法論據是不變的。

+0

ok對於字符串值,但是爲什麼對於enum的整數值呢? – Zonko 2012-04-13 09:46:27

+0

@Zonko文化問題? – 2012-04-13 09:48:13

+0

@Zonko,編譯時會自動調用整數值上的'int32.ToString()',以在連接字符串之前將其轉換爲字符串。 – 2012-04-13 09:48:18

2

你不能這樣做,因爲MyEnum.Value1(int)MyEnum.Value1不是常數string值。在分配時將會有一個隱式轉換。

使用static readonly string代替:

static readonly string blah = "blah " + MyEnum.Value1;