c# - 我可以在 C# 中从 const char 初始化 const 字符串吗?

标签 c# string constants

我正在尝试以某种方式执行以下操作:

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/

相关文章:

c# - 我可以向函数添加属性以防止重新进入吗?

php - 在 PHP 中清理合法变量名称的字符串

string - R - 获取给定时间段内最常见的字符串值(模式)

java - 我需要数组方面的帮助,将用户输入分配给数组,以及 do-while 循环重复

c++ - 如何正确使用外部变量?

if-statement - Struts 2 如果标签 : test with a constant

c# - 在c#中删除多种文件类型的文件

c# - 在 C# 4.0 中使用依赖注入(inject)时处理异常

c# - 将 SqlDependency 与命名队列一起使用

c# - 从字符串中提取值