C# enum contains value

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

    I think that you go wrong when using ToString().

    Try making a Linq query

    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;
    }
    
    0 讨论(0)
  • 2020-12-08 00:27

    What you're doing with ToString() in this case is to:

    Enum.GetValues(typeof(myEnum)).ToString()... instead you should write:

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

    The difference is in the parentheses...

    0 讨论(0)
  • No need to write your own:

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

    Example:

    if (System.Enum.IsDefined(MyEnumType, MyValue))
    {
        // Do something
    }
    
    0 讨论(0)
  • 2020-12-08 00:28

    just cast the enum as:

    string something = (string)myEnum;
    

    and now comparison is easy as you like

    0 讨论(0)
  • 2020-12-08 00:29

    Use the correct name of the enum (myEnum2).

    Also, if you're testing against a string value you may want to use GetNames instead of GetValues.

    0 讨论(0)
  • 2020-12-08 00:38

    just use this method

    Enum.IsDefined Method - Returns an indication whether a constant with a specified value exists in a specified enumeration

    Example

    enum myEnum2 { ab, st, top, under, below};
    myEnum2 value = myEnum2.ab;
     Console.WriteLine("{0:D} Exists: {1}", 
                            value, myEnum2.IsDefined(typeof(myEnum2), value));
    
    0 讨论(0)
提交回复
热议问题