C# enum contains value

后端 未结 10 663
轮回少年
轮回少年 2020-12-07 23:46

I have an enum

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

I would like to write a function to test if a given value is included in myEnum

10条回答
  •  庸人自扰
    2020-12-08 00:42

    If your question is like "I have an enum type, enum MyEnum { OneEnumMember, OtherEnumMember }, and I'd like to have a function which tells whether this enum type contains a member with a specific name, then what you're looking for is the System.Enum.IsDefined method:

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

    If your question is like "I have an instance of an enum type, which has Flags attribute, and I'd like to have a function which tells whether this instance contains a specific enum value, then the function looks something like this:

    public static bool ContainsValue(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;
    }
    

    Hope I could help.

提交回复
热议问题