枚举。带标记枚举的定义 [英] Enum.IsDefined with flagged enums
问题描述
我目前正在阅读这本书 C#4.0 in a Nutshell ,其中我认为是一个优秀的书,甚至为高级程序员使用作为一个很好的参考。
我回顾了关于基础的章节,我遇到了一个诡计,使用带标记的枚举时,在枚举中定义了某个值。<
该书声明,使用 Enum.IsDefined
在标记的枚举中不起作用,建议这样一个工作:
static bool IsFlagDefined(Enum e)
{
decimal d ;
return(!decimal.TryParse(e.ToString(),out d);
}
如果在标记的枚举中定义了某个值,则应该返回true。
有人可以向我解释为什么这个工作吗? >
提前感谢:)
基本上,调用 c> c> 的
[To] 对任何定义的值返回这样的值:
SomeValue,SomeOtherValue
$另一方面,如果值 在
枚举
类型中定义,则,则
ToString
将简单地生成该值的整数值的字符串表示,例如:5
解析
ToString
的输出作为一个数字(不知道为什么作者选择decimal
),类型。
下面是一个例子:
b $ b enum SomeEnum
{
SomeValue = 1,
SomeOtherValue = 2,
SomeFinalValue = 4
}
public class Program
{
public static void Main()
{
//这是定义的。
SomeEnum x = SomeEnum.SomeOtherValue | SomeEnum.SomeFinalValue;
Console.WriteLine(x);
//这不是(1,2和4的按位组合不会产生8)。
x =(SomeEnum)8;
Console.WriteLine(x);
}
}
上述程序的输出是:
SomeOtherValue,SomeFinalValue
8
您可以看到建议的方法是如何工作的。
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 usingEnum.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 :)
解决方案Basically, calling
ToString
on anyenum
value of a type declared with the[Flags]
attribute will return something like this for any defined value:SomeValue, SomeOtherValue
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.:5
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:
[Flags] enum SomeEnum { SomeValue = 1, SomeOtherValue = 2, SomeFinalValue = 4 } public class Program { public static void Main() { // This is defined. SomeEnum x = SomeEnum.SomeOtherValue | SomeEnum.SomeFinalValue; Console.WriteLine(x); // This is not (no bitwise combination of 1, 2, and 4 will produce 8). x = (SomeEnum)8; Console.WriteLine(x); } }
The output of the above program is:
SomeOtherValue, SomeFinalValue 8So you can see how the suggested method works.
这篇关于枚举。带标记枚举的定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!