我正在尝试以某种方式执行以下操作:
const char EscapeChar = '\\';
const string EscapeString = EscapeChar.ToString(); // or ("" + EscapeChar)
这不会编译。还有其他方法可以让它发挥作用吗?
最佳答案
来自C# Language Specification (§ 17.3 和 14.16):
17.3 Constants
A constant is a class member that represents a constant value: a value that can be computed at compile-time.
和
14.16 Constant expressions
A constant expression is an expression that shall be fully evaluated at compile-time. Where an expression is required to be constant this is indicated in the grammar by using constant-expression. [...] The following constructs are permitted in constant expressions:
- Literals (including the null literal)
- References to const members of class and struct types.
- References to members of enumeration types.
- Parenthesized sub-expressions, which are themselves constant expressions.
- Cast expressions, provided the target type is one of the types listed above.
- The predefined checked and unchecked, +, –, !, and ~ unary operators.
- The predefined +, –, *, /, %, <<, >>, &, |, ^, &&, ||, ==, !=, <, >, <=, and >= binary operators, provided each operand is of a type listed above.
- The ?: conditional operator.
- sizeof expressions, provided the unmanaged-type is one of the types specified in §14.5.12.
- default value expressions, provided the type is one of the types listed above, or the type is a reference type or a type parameter that is known to be a reference type (§25.7).
The following conversions are permitted in constant expressions:
- Identity conversions
- Numeric conversions
- Enumeration conversions
另一种实现您想要的方法是使用静态只读成员。只读成员在运行时评估,而不是在编译时评估。因此,您可以使用 ToString() 方法。
private static readonly EscapeString = EscapeChar.ToString();
注意:因为只读字段可以在类的声明中或构造函数中初始化,所以只读字段可以根据所使用的构造函数不同具有不同的值。
这是一篇关于 differences between const and readonly members 的好文章.
关于c# - 我可以在 C# 中从 const char 初始化 const 字符串吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/410692/