如何在常量字符串中包含枚举值

本文关键字:包含 枚举 字符串 常量 | 更新日期: 2023-09-27 18:30:55

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

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

或这个:

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

您将如何在常量字符串中包含枚举值?

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

如何在常量字符串中包含枚举值

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

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

至于为什么:对于枚举情况,枚举格式化实际上非常复杂,特别是对于[Flags]的情况,所以把它留给运行时是有意义的。对于int情况,这仍然可能受到区域性特定问题的影响,因此再次:需要推迟到运行时。编译器实际生成的是一个盒子操作,即使用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).

您需要

使用readonlystatic readonly而不是const

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

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

你不能

这样做,因为MyEnum.Value1(int)MyEnum.Value1不是常量string值。分配时将进行隐式转换。

请改用static readonly string

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