我知道我可以通过连接其他常量字符串来创建新的常量字符串:
const string a = "A";
const string ab = a + "B";
是否有可能基于常量 int 创建常量字符串?例如,以下不会编译:
const int Dpi = 300;
const string DeviceInfo = "<DeviceInfo><Dpi>" + Dpi + "</Dpi></DeviceInfo>";
The expression assigned to MyClass.DeviceInfo must be constant.
我知道我可以解决这个问题
- 使
Dpi
成为字符串而不是 int(并在我需要 int 值时int.Parse
处理它), - 添加第二个字符串常量
DpiString
(因此违反 DRY),或 - 使
DeviceInfo
成为static readonly
字段而不是const
字段。
我打算选择选项 3,但是,出于好奇,我想知道是否还有其他我错过的选项...
最佳答案
不,字符串常量不能是在运行时求值的表达式。
The following conversions are permitted in constant expressions:
- Identity conversions
- Numeric conversions
- Enumeration conversions
- Constant expression conversions
- Implicit and explicit reference conversions, provided that the source of the conversions is a constant expression that evaluates to the null value.
Other conversions including boxing, unboxing and implicit reference conversions of non-null values are not permitted in constant expressions.
将 int
转换为 string
属于不允许的“其他转换”,因为这需要调用 ToString()
方法。
事实上,转换需要调用定义为使用 G10
数字格式的 int.ToString()
。这取决于当前区域性的 NumberFormatInfo.NegativeSign
,因此原则上可能会发生变化。除了 \u002d
hyphen-minus character,我不知道有任何默认文化使用任何东西作为负号,但如果你想看到世界燃烧。
关于c# - 我可以通过在 C# 中连接字符串和 int 常量来创建字符串常量吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47606704/