C#enum包含值

Fre*_*ith 60 c# enums contains

我有一个枚举

enum myEnum2 { ab, st, top, under, below}
Run Code Online (Sandbox Code Playgroud)

我想编写一个函数来测试myEnum中是否包含给定值

类似的东西:

private bool EnumContainValue(Enum myEnum, string myValue)
{
     return Enum.GetValues(typeof(myEnum))
                .ToString().ToUpper().Contains(myValue.ToUpper()); 
}
Run Code Online (Sandbox Code Playgroud)

但它不起作用,因为无法识别myEnum参数.

Ser*_*kiy 90

为什么不用

Enum.IsDefined(typeof(myEnum), value);
Run Code Online (Sandbox Code Playgroud)

BTW很高兴创建泛型Enum<T>类,它包含调用Enum(实际上我想知道为什么这样的东西没有添加到Framework 2.0或更高版本):

public static class Enum<T>
{
    public static bool IsDefined(string name)
    {
        return Enum.IsDefined(typeof(T), name);
    }

    public static bool IsDefined(T value)
    {
        return Enum.IsDefined(typeof(T), value);
    }

    public static IEnumerable<T> GetValues()
    {
        return Enum.GetValues(typeof(T)).Cast<T>();
    }
    // etc
}
Run Code Online (Sandbox Code Playgroud)

这允许避免所有这些typeof东西并使用强类型值:

Enum<StringSplitOptions>.IsDefined("None")
Run Code Online (Sandbox Code Playgroud)


Lig*_*ker 46

无需编写自己的:

    // Summary:
    //     Returns an indication whether a constant with a specified value exists in
    //     a specified enumeration.
    //
    // Parameters:
    //   enumType:
    //     An enumeration type.
    //
    //   value:
    //     The value or name of a constant in enumType.
    //
    // Returns:
    //     true if a constant in enumType has a value equal to value; otherwise, false.

    public static bool IsDefined(Type enumType, object value);
Run Code Online (Sandbox Code Playgroud)

例:

if (System.Enum.IsDefined(MyEnumType, MyValue))
{
    // Do something
}
Run Code Online (Sandbox Code Playgroud)


Pra*_*ana 10

只是使用这种方法

Enum.IsDefined Method - 返回指示指定枚举中是否存在具有指定值的常量的指示

enum myEnum2 { ab, st, top, under, below};
myEnum2 value = myEnum2.ab;
 Console.WriteLine("{0:D} Exists: {1}", 
                        value, myEnum2.IsDefined(typeof(myEnum2), value));
Run Code Online (Sandbox Code Playgroud)