【问题标题】:How to include an enum value in a const string?如何在 const 字符串中包含枚举值?
【发布时间】:2012-04-25 16:17:41
【问题描述】:

this question,我知道const string 可以是const 事物的串联。现在,枚举只是一组连续整数,不是吗? 那么为什么不能这样做:

const string blah = "blah " + MyEnum.Value1;

或者这个:

const string bloh = "bloh " + (int)MyEnum.Value1;

如何在 const 字符串中包含枚举值?

现实生活中的例子:在构建 SQL 查询时,我想要"where status <> " + StatusEnum.Discarded

【问题讨论】:

  • 猜测原因:连接整数可能涉及文化依赖性问题。您的int.ToString() 可能与我的int.ToString() 不同。可能。只是一个猜测。尤其是负数,可能。
  • 哦,对了,我没有仔细阅读我链接的问题。所以这不仅仅是枚举,实际上也不可能在 const 字符串中包含 const 整数。
  • 是的; const string foo = "abc" + 1; 同样失败

标签: c# string enums constants


【解决方案1】:

作为一种解决方法,您可以使用字段初始值设定项而不是 const,即

static readonly string blah = "blah " + MyEnum.Value1;

static readonly string bloh = "bloh " + (int)MyEnum.Value1;

至于为什么:对于 enum 的情况,enum 格式化实际上是相当复杂的,尤其是对于 [Flags] 的情况,因此将其留给运行时是有意义的。对于int 的情况,这仍然可能受到文化特定问题的影响,所以再次:需要推迟到运行时。编译器实际上生成的是这里的box操作,即使用string.Concat(object,object)重载,等同于:

static readonly string blah = string.Concat("blah ", MyEnum.Value1);
static readonly string bloh = string.Concat("bloh ", (int)MyEnum.Value1);

string.Concat 将执行.ToString()。因此,可以说以下方法效率更高(避免使用框和虚拟调用):

static readonly string blah = "blah " + MyEnum.Value1.ToString();
static readonly string bloh = "bloh " + ((int)MyEnum.Value1).ToString();

这将使用string.Concat(string,string)

【讨论】:

    【解决方案2】:

    您需要使用readonlystatic readonly 而不是const

    static readonly string blah = "blah " + MyEnum.Value1;
    

    MyEnum.Value1 不被视为const 的原因是需要调用方法将值转换为字符串,并且方法调用的结果不会被视为常量值,即使方法参数是常数。

    【讨论】:

    • 字符串值没问题,但为什么枚举的整数值呢?
    • @Zonko,编译后会自动在整数值上调用int32.ToString(),在连接字符串之前将其转换为字符串。
    • @Albin 实际上,不;编译器boxes并调用string.Concat(object,object)编译器根本不调用.ToString()
    【解决方案3】:

    您不能这样做,因为MyEnum.Value1(int)MyEnum.Value1 不是恒定的string 值。赋值时会有隐式转换。

    改用static readonly string

    static readonly string blah = "blah " + MyEnum.Value1;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-08-09
      • 2020-03-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多