C#enum包含值

时间:2012-11-06 10:16:56

标签: c# enums contains

我有一个枚举

enum myEnum2 { ab, st, top, under, below}

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

类似的东西:

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

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

10 个答案:

答案 0 :(得分:87)

为什么不使用

Enum.IsDefined(typeof(myEnum), value);

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
}

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

Enum<StringSplitOptions>.IsDefined("None")

答案 1 :(得分:43)

无需自己编写:

    // 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);

示例:

if (System.Enum.IsDefined(MyEnumType, MyValue))
{
    // Do something
}

答案 2 :(得分: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));

答案 3 :(得分:3)

在这种情况下,您使用ToString()所做的是:

Enum.GetValues(typeof(myEnum)).ToString()...而你应该写:

Enum.GetValues(typeof(myEnum).ToString()...

区别在于括号......

答案 4 :(得分:2)

也可以使用这个:

    enum myEnum2 { ab, st, top, under, below }
    static void Main(string[] args)
    {
        myEnum2 r;
        string name = "ab";
        bool result = Enum.TryParse(name, out r);
    }

结果将包含该值是否包含在枚举中。

答案 5 :(得分:2)

   public static T ConvertToEnum<T>(this string value)
    {
        if (typeof(T).BaseType != typeof(Enum))
        {
            throw new InvalidCastException("The specified object is not an enum.");
        }
        if (Enum.IsDefined(typeof(T), value.ToUpper()) == false)
        {
            throw new InvalidCastException("The parameter value doesn't exist in the specified enum.");
        }
        return (T)Enum.Parse(typeof(T), value.ToUpper());
    }

答案 6 :(得分:2)

如果您的问题类似于&#34;我有一个枚举类型enum MyEnum { OneEnumMember, OtherEnumMember },并且我想要一个函数来判断此枚举类型是否包含具有特定名称的成员,那么您正在寻找的是System.Enum.IsDefined方法:

Enum.IsDefined(typeof(MyEnum), MyEnum.OneEnumMember); //returns true
Enum.IsDefined(typeof(MyEnum), "OtherEnumMember"); //returns true
Enum.IsDefined(typeof(MyEnum), "SomethingDifferent"); //returns false

如果你的问题是&#34;我有一个枚举类型的实例,它有Flags属性,我想要一个函数告诉这个实例是否包含一个特定的枚举值,那么函数看起来像这样:

public static bool ContainsValue<TEnum>(this TEnum e, TEnum val) where Enum: struct, IComparable, IFormattable, IConvertible
{
    if (!e.GetType().IsEnum)
        throw new ArgumentException("The type TEnum must be an enum type.", nameof(TEnum));

    dynamic val1 = e, val2 = val;
    return (val1 | val2) == val1;
}

希望我能提供帮助。

答案 7 :(得分:1)

使用枚举的正确名称(myEnum2)。

此外,如果您正在测试字符串值,则可能需要使用GetNames而不是GetValues

答案 8 :(得分:1)

将枚举转换为:

string something = (string)myEnum;

现在可以轻松比较

答案 9 :(得分:1)

我认为使用ToString()时出错了。

尝试制作Linq查询

private bool EnumContainValue(Enum myEnum, string myValue)
{
    var query = from enumVal in Enum.GetNames(typeof(GM)).ToList()
                       where enumVal == myValue
                       select enumVal;

    return query.Count() == 1;
}