【问题标题】:The Expression assigned to X must be constant分配给 X 的表达式必须是常量
【发布时间】:2013-03-18 10:23:50
【问题描述】:

我遇到了这个问题并正在寻找解决方案,但没有找到与我类似的情况。以下是我的情况:

在 X.cs 类文件中:

namespace BlaBla{

  public class X{
    public const string foo = "foo";
    // other code
  }

  public class Y{
    public const int bar = 0;
  }
}

在其他课程中,我正在写作:

private const string someString = X.foo + Y.bar + "";

它一直给我一个编译错误:

The Expression assigned to someString must be constant

虽然它们都是不变的!当我删除 Y.bar 时,错误被删除,我不知道为什么。有什么帮助吗?

【问题讨论】:

    标签: c# compiler-errors constants


    【解决方案1】:

    您使用的 const 关键字错误。您可能希望将someString 定义为:

    private readonly someString = X.foo + Y.bar;
    

    当变量被标记为const 时,它们会被编译到程序集中然后进行优化。虽然Y.bar 被定义为const,但您隐式调用了它的ToString() 方法,这使得它不是常量。

    【讨论】:

      【解决方案2】:

      您将包含从int 到string 的转换。即使int 是一个常量,转换也不被视为常量表达式。

      您可以更简单地证明这一点:

      class Test
      {
          const int X = 10;
          const string Y = "X: " + X;
      }
      

      有关什么是常量表达式的更多详细信息,请参阅 C# 规范的第 7.19 节。

      【讨论】:

        【解决方案3】:

        表达式看起来不变,但它需要求值才能计算出值。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-02-09
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多