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 - 在 C 和 GCC 中使用带有返回参数的 pure/const 属性?

c++ - 为什么 SFINAE 在更改类模板特化的位置时会搞砸?这是 C++ 错误吗?

c - 如果两种类型在 C 中彼此为 "compatible",这究竟意味着什么?

c++ - dladdr : pointer-to-function vs pointer-to-object

c# - 将 System.Drawing.Icon 转换为 SkiaSharp.SKBitmap

c# - 如何从上到下键入数据(最上面的应该是新帖子,最后一个应该是最旧的)asp.net c#

c# - SQLite 数据库在执行 alter table 查询 C# 时被锁定

c# - SetValue 64 位机器注册表

C# const 保护与内部

c++ - 使用 `const reference` 在显式构造函数中分配 `std::vector` 成员不是持久的