c# - Enum.IsDefined 带有标记的枚举

标签 c# c#-4.0 enums flags

我正在读这本书 C# 4.0 in a Nutshell ,顺便说一下,我认为这是一本优秀的书,即使是高级程序员也可以作为很好的引用。

我在回顾有关基础知识的章节时,遇到了一个技巧,可以在使用带标记的枚举时判断某个值是否在枚举中定义。
该书指出使用 Enum.IsDefined 不适用于标记的枚举,并建议像这样的解决方法:

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

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

有人可以向我解释为什么这有效吗?

提前致谢:)

最佳答案

基本上,对使用 [Flags] 属性声明的类型的任何 enum 值调用 ToString 将为任何已定义的类型返回类似这样的内容值:

SomeValue, SomeOtherValue

另一方面,如果该值enum 类型中定义,则ToString 将简单地生成该值的字符串表示形式值的整数值,例如:

5

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

这是一个例子:

[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);
    }
}

上述程序的输出是:

SomeOtherValue, SomeFinalValue
8

这样您就可以看到建议的方法是如何工作的。

关于c# - Enum.IsDefined 带有标记的枚举,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4950001/

相关文章:

c# - 为什么 Ajax.BeginForm 在 Chrome 中不起作用?

sql-server - TransactionScope 锁定表和 IsolationLevel

wpf - 逻辑组合依赖属性

ios - 在类型中找不到枚举大小写开关

c - #defined 位标志和枚举 - 在 "c"中和平共处

c# - 我可以获得代码契约(Contract)来警告我有关 "illegal"子类型的信息吗?

c# - 日期时间不会过滤到 Angular 中的时间。

sorting - 如何在 dapper 扩展中使用 DESC 顺序根据 Order by 子句对数据进行排序?

C# 将 int 类型的对象转换为可为 null 的枚举

c# - 在运行时使用和调用 SOAP Web 服务 - 来自 WSDL 文件的动态 Web 服务客户端