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

2023-11-26

from 这个问题,我知道一个const string可以是以下的串联const事物。现在,枚举只是一组连续的整数,不是吗? 那么为什么这样做不行呢:

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

或这个 :

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

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

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


As a 解决方法,您可以使用字段初始值设定项而不是 const,即

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

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

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

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

where string.Concat将执行.ToString()。因此,可以说以下方法稍微更有效(避免了盒子和虚拟调用):

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

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

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在 const 字符串中包含枚举值? 的相关文章

随机推荐