Enum.IsDefined 带有标记的枚举
我目前正在阅读C# 4.0 in a Nutshell这本书,顺便说一句我认为是一本很棒的书,甚至对于高级程序员来说也可以作为很好的参考。
我回顾了有关基础知识的章节,发现了一个技巧来判断在使用标记枚举时是否在枚举中定义了某个值。
该书指出,使用 Enum.IsDefined
不适用于标记的枚举,并建议采用如下解决方法:
static bool IsFlagDefined(Enum e)
{
decimal d;
return (!decimal.TryParse(e.ToString(), out d);
}
如果在标记的枚举中定义了某个值,则应返回 true。
有人可以向我解释为什么这有效吗?
提前致谢 :)
I'm currently reading the book C# 4.0 in a Nutshell, which by the way I think is an excellent book, even for advanced programmers to use as a good reference.
I was looking back on the chapters about the basics, and I came across a trick to tell if a certain value is defined in an Enum when using flagged enums.
The book states that using Enum.IsDefined
doesn't work on flagged enums, and suggests a work-around like this :
static bool IsFlagDefined(Enum e)
{
decimal d;
return (!decimal.TryParse(e.ToString(), out d);
}
This should return true if a certain value is defined in an enum which is flagged.
Can someone please explain to me why this works ?
Thanks in advance :)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
基本上,对使用
[Flags]
属性声明的类型的任何enum
值调用ToString
将为任何定义的值返回类似以下内容:另一方面,如果该值未在
enum
类型中定义,则ToString
将简单地生成该值的字符串表示形式整数值,例如:所以这意味着如果你可以将
ToString
的输出解析为数字(不确定作者为什么选择decimal
),它没有在类型中定义。这是一个例子:
上述程序的输出是:
因此您可以看到建议的方法是如何工作的。
Basically, calling
ToString
on anyenum
value of a type declared with the[Flags]
attribute will return something like this for any defined value:On the other hand, if the value is not defined within the
enum
type, thenToString
will simply produce a string representation of that value's integer value, e.g.:So what this means is that if you can parse the output of
ToString
as a number (not sure why the author chosedecimal
), it isn't defined within the type.Here's an illustration:
The output of the above program is:
So you can see how the suggested method works.
如果
e
的值不能使用标志组合创建,则ToString()
默认为整数。整数当然会解析为小数
。但是我并不完全清楚为什么你的代码解析为十进制。但整数类型可能不适用于基于
Int64
和UInt64
的enum
。If the value of
e
isn't can't be created using a combination of flagsToString()
defaults to an integral number. And integral numbers will of course parse asdecimal
.But why your code parses as decimal isn't entirely clear to me. But probably integral types won't work for both
enum
s that are based inInt64
andUInt64
.