據我所知,"H" + 'i'
的連接產生一個常量字符串。
我或C#錯了嗎?爲什麼不能將常量字符串分配給常量字符串類型?
代碼:
const string b = "H" + 'i';
// Error : The expression being assigned to 'b' must be constant
這是否算作一個錯誤或功能?
據我所知,"H" + 'i'
的連接產生一個常量字符串。
我或C#錯了嗎?爲什麼不能將常量字符串分配給常量字符串類型?
代碼:
const string b = "H" + 'i';
// Error : The expression being assigned to 'b' must be constant
這是否算作一個錯誤或功能?
這是一個微妙之處。
'i'
是char字面值。
將其添加到字符串涉及裝箱轉換(要按規範中的規定,請致電string operator +(string x, object y)
),它不是一個常量表達式。請參閱我的earlier answer。
也許VS2010錯誤將幫助定義它:
Constant initializer must be compile-time constant
因此 「H」 + 'i' 是一個運行值。
這並不能解釋爲什麼。 '「H」+「i」'很好。 – SLaks 2013-02-26 20:09:34
@SLaks,真的,我喜歡你的「早期答案」,它對此進行了深入的解釋。 – 2013-02-26 20:11:50
您不會添加兩個字符串,而是一個字符串和一個字符。 – ChrisF 2013-02-26 20:07:42
char不是一個字符串,因此它不是一個常量。這將工作:'const string b =「H」+「 i」;' – 2013-02-26 20:08:05