Zon*_*nko 7 c# string enums const
从这个问题,我知道一个const string可以是const事物的连接.现在,一个枚举只是一组续整数,不是吗?那么为什么不能这样做:
const string blah = "blah " + MyEnum.Value1;
Run Code Online (Sandbox Code Playgroud)
或这个 :
const string bloh = "bloh " + (int)MyEnum.Value1;
Run Code Online (Sandbox Code Playgroud)
你如何在const字符串中包含枚举值?
现实生活中的例子:在构建SQL查询时,我想拥有"where status <> " + StatusEnum.Discarded.
作为一种解决方法,您可以使用字段初始值设定项而不是const,即
static readonly string blah = "blah " + MyEnum.Value1;
static readonly string bloh = "bloh " + (int)MyEnum.Value1;
Run Code Online (Sandbox Code Playgroud)
至于原因:对于枚举情况,枚举格式实际上非常复杂,特别是对于这种[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);
Run Code Online (Sandbox Code Playgroud)
string.Concat将在哪里执行.ToString().因此,可以说下面的效率稍高一些(避免使用盒子和虚拟呼叫):
static readonly string blah = "blah " + MyEnum.Value1.ToString();
static readonly string bloh = "bloh " + ((int)MyEnum.Value1).ToString();
Run Code Online (Sandbox Code Playgroud)
哪个会用string.Concat(string,string).