【问题标题】:How to create const string from string variable如何从字符串变量创建 const 字符串
【发布时间】:2012-12-13 14:15:00
【问题描述】:

我想从另一个字符串变量创建 const 字符串。比如下面两个代码sn-ps就编译不了

1)

string str = "111";
const string str2 = str;

2)

string str = "111";
const string str2 = new string(str.ToCharArray());

结果

Error: The expression being assigned to 'str2' must be constant 

有没有办法从字符串变量创建一个 const 字符串?

【问题讨论】:

  • 在编译过程中必须完全知道常量变量,所以这是不可能的。
  • 使用 readonly 关键字代替 const
  • 在这些情况下static readonly 可以帮助替代。

标签: c# string constants


【解决方案1】:

简而言之 - 没有。

分配给const 的值必须是编译时间常数。

您可以使用readonly 代替const,这样您就可以更改变量的值 - 您只能在构造函数中更改引用。

【讨论】:

    【解决方案2】:

    常量是在编译时评估的,所以你想要的是不可能的。但是,您可以将常量替换为只读,例如:

    string s = "Hello";
    readonly string t = s + " World";
    

    【讨论】:

      【解决方案3】:

      使用只读关键字。

      string str = "111";
      readonly string str2 = str.ToCharArray();
      

      【讨论】:

        【解决方案4】:

        不。因为const 变量在编译时起作用。

        大家都同意使用readonly

        readonly string t = s + " World";
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2014-03-03
          • 1970-01-01
          • 1970-01-01
          • 2019-11-24
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多