如何在一个const字符串中包含枚举值? [英] How to include an enum value in a const string?
问题描述
从这个问题,我知道一个 const string
可以是 const
的连接。现在,枚举只是一组连续整数,不是吗?
那么为什么不这样做:
from this question, I know that a const string
can be the concatenation of const
things. Now, an enum is just a set of cont integers, isn't it ?
So why isn't it ok to do this :
const string blah = "blah " + MyEnum.Value1;
或此:
const string bloh = "bloh " + (int)MyEnum.Value1;
您将如何在一个const字符串中包含枚举值?
And how would you include an enum value in a const string ?
现实生活中的例子:构建SQL查询时,我想要where status<>+ StatusEnum.Discarded
p>
Real life example : when building an SQL query, I would like to have "where status <> " + StatusEnum.Discarded
.
推荐答案
作为一个解决方法,您可以使用字段初始化器而不是const,即
As a workaround, you can use a field initializer instead of a const, i.e.
static readonly string blah = "blah " + MyEnum.Value1;
static readonly string bloh = "bloh " + (int)MyEnum.Value1;
至于为什么:对于枚举案例,枚举格式实际上很漂亮复杂,特别是对于 [Flags]
case,所以把它留给运行时是有意义的。对于 int
案例,这仍然可能会受文化特定问题的影响,因此再次需要延迟到运行时。编译器实际生成的是一个框操作,即使用 string.Concat(object,object)
overload ,相同:
As for why: for the enum case, enum formatting is actually pretty complex, especially for the [Flags]
case, so it makes sense to leave this to the runtime. For the int
case, this could still potentially be affected by culture specific issues, so again: needs to be deferred until runtime. What the compiler actually generates is a box operation here, i.e. using the string.Concat(object,object)
overload, identical to:
static readonly string blah = string.Concat("blah ", MyEnum.Value1);
static readonly string bloh = string.Concat("bloh ", (int)MyEnum.Value1);
其中 string.Concat
将执行的ToString()
。因此,可以认为以下是稍微有效的(避免一个框和一个虚拟调用):
where string.Concat
will perform the .ToString()
. As such, it could be argued that the following is slightly more efficient (avoids a box and a virtual call):
static readonly string blah = "blah " + MyEnum.Value1.ToString();
static readonly string bloh = "bloh " + ((int)MyEnum.Value1).ToString();
它将使用 string.Concat(string,string)
。
这篇关于如何在一个const字符串中包含枚举值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!