c# - 我可以通过在 C# 中连接字符串和 int 常量来创建字符串常量吗?

标签 c# constants language-lawyer

我知道我可以通过连接其他常量字符串来创建新的常量字符串:

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.

我知道我可以解决这个问题

  1. 使 Dpi 成为字符串而不是 int(并在我需要 int 值时 int.Parse 处理它),
  2. 添加第二个字符串常量 DpiString(因此违反 DRY),或
  3. 使 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/

相关文章:

c# - Chrome 使用与 Visual Studio 不同的 localhost SSL 证书

ruby-on-rails - ruby on rails,变量后面或前面的冒号

c - 预处理器算术是否应该与编译所针对的体系结构相匹配?

c# - 使用样式应用多个 AttachedCommandBehavior

c# - 在模型 .net 核心 web api 中返回具有 null 必需属性的 BadRequest

c# - response.redirect 并抛出 catch block

c++ - 在类的函数中使用 'const'

C++ - 引用参数的常量值?

c++ - C++11 是否允许在标识符中使用美元符号?

c - 结构成员初始化之间是否有顺序点?