C# enum contains value

后端 未结 10 679
轮回少年
轮回少年 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:44

    Why not use

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

    BTW it's nice to create generic Enum class, which wraps around calls to Enum (actually I wonder why something like this was not added to Framework 2.0 or later):

    public static class Enum
    {
        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 GetValues()
        {
            return Enum.GetValues(typeof(T)).Cast();
        }
        // etc
    }
    

    This allows to avoid all this typeof stuff and use strongly-typed values:

    Enum.IsDefined("None")
    

提交回复
热议问题