为什么不能将常量字符串赋值给常量字符串类型?
本文关键字:常量 字符串 类型 赋值 不能 为什么 | 更新日期: 2023-09-27 18:01:28
据我所知,"H" + 'i'
的连接产生一个常量字符串。
是我错了还是c#错了?
代码:
const string b = "H" + 'i';
// Error : The expression being assigned to 'b' must be constant
这是一个bug还是一个特性?
这很微妙。
'i'
是char字面值。
将它添加到字符串中涉及到装箱转换(调用string operator +(string x, object y)
,如规范中指定的),这不是一个常量表达式。
也许VS2010错误将有助于定义它:
Constant initializer must be compile-time constant
所以"H" + " i "是一个运行时值