枚举。带标记枚举的定义 [英] Enum.IsDefined with flagged enums

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

问题描述

我目前正在阅读这本书 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 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天全站免登陆