Why does Enum.Parse create undefined entries?

后端 未结 4 1187
孤独总比滥情好
孤独总比滥情好 2020-12-20 17:09
class Program
{
    static void Main(string[] args)
    {
        string value = "12345";
        Type enumType = typeof(Fruits);
        Fruits fruit = Fr         


        
4条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-20 17:49

    An enum can be any value of its base integer type. It is not just restricted to named constants.

    For instance, the following is perfectly valid:

    enum Foo{
        A,
        B,
        C,
        D
    }
    
    Foo x = (Foo)5;
    

    Even though 5 does not correspond to a named constant, it is still a valid value for Foo, since the underlying type for Foo is Int32.

    If one were to call x.ToString(), the returned value would be simply "5", since no named constant corresponds with x's value.

    Enum.Parse() is the converse function of Enum.ToString(). You should expect that whatever Enum.ToString() can return that Enum.Parse() can accept. This includes, for instance, comma-separated values for flags enums:

    [Flags]
    enum Foo{
        A = 1,
        B = 2,
        C = 4,
        D = 8
    }
    
    Foo x = Foo.A | Foo.B | Foo.C | Foo.D;
    int i = (int)x;
    string s = x.ToString();
    Console.WriteLine(i);
    Console.WriteLine(s);
    Console.WriteLine((Foo)Enum.Parse(typeof(Foo), i.ToString()) == x);
    Console.WriteLine((Foo)Enum.Parse(typeof(Foo), s) == x);
    

    Output:

    15
    A, B, C, D
    True
    True
    

    EDIT:

    What you really seem to want is something like this:

    static Enum GetEnumValue(Type enumType, string name){
        // null-checking omitted for brevity
    
        int index = Array.IndexOf(Enum.GetNames(enumType), name);
        if(index < 0)
            throw new ArgumentException("\"" + name + "\" is not a value in " + enumType, "name");
    
        return Enum.GetValues(enumType).GetValue(index);
    }
    

    or a case-insensitive version:

    static Enum GetEnumValue(Type enumType, string name, bool ignoreCase){
        // null-checking omitted
    
        int index;
        if(ignoreCase)
            index = Array.FindIndex(Enum.GetNames(enumType),
                s => string.Compare(s, name, StringComparison.OrdinalIgnoreCase) == 0);
                // or StringComparison.CurrentCultureIgnoreCase or something if you
                // need to support fancy Unicode names
        else index = Array.IndexOf(Enum.GetNames(enumType), name);
    
        if(index < 0)
            throw new ArgumentException("\"" + name + "\" is not a value in " + enumType, "name");
    
        return Enum.GetValues(enumType).GetValue(index);
    }
    

提交回复
热议问题