枚举。定义枚举枚举 [英] Enum.IsDefined with flagged enums

查看:111
本文介绍了枚举。定义枚举枚举的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在读书 C#4.0 in a Nutshell ,其中由我认为这是一本很好的书,即使是高级程序员也可以作为一个很好的参考。



我回顾了有关基础的章节,我遇到了一个在使用标记的枚举时,告诉您在枚举中是否定义了某个值。_
该书指出使用 Enum.IsDefined 不起作用在标记的枚举上,并建议一个这样的工作:

  static bool IsFlagDefined(Enum e)
{
十进制d;
return(!decimal.TryParse(e.ToString(),out d);
}

如果在被标记的枚举中定义了某个值,则返回true。



有人可以向我解释为什么这样工作吗? >

提前感谢:)

解决方案

基本上,调用 [Flags] 属性声明的类型的任何枚举值上的ToString 将会对于任何定义的值返回类似的东西:

  SomeValue,SomeOtherValue 

另一方面,如果枚举类型中定义的值 ,那么 ToString 将简单地生成该值的整数值的字符串表示,例如:

  5 

那么这意味着如果你可以将 ToString 的输出解析为一个数字(不知道为什么auth或者选择 decimal ),它没有在类型中定义。



这是一个例证:

  [Flags] 
枚举SomeEnum
{
SomeValue = 1,
SomeOtherValue =
SomeFinalValue = 4
}

public class Program
{
public static void Main()
{
// This被定义为。
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 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 :)

解决方案

Basically, calling ToString on any enum 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, then ToString 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 chose decimal), 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
8

So you can see how the suggested method works.

这篇关于枚举。定义枚举枚举的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆