Parse string to enum type

后端 未结 8 1197
灰色年华
灰色年华 2020-11-29 09:04

I have an enum type like this as an example:

public Enum MyEnum {
    enum1, enum2, enum3 };

I\'ll read a string from config file. What I n

8条回答
  •  失恋的感觉
    2020-11-29 09:47

    private enum MyEnum
    {
        Enum1 = 1, Enum2 = 2, Enum3 = 3, Enum4 = 4, Enum5 = 5, Enum6 = 6, 
        Enum7 = 7, Enum8 = 8, Enum9 = 9, Enum10 = 10
    }
    
    private static Object ParseEnum(string s)
    {
        try
        {
            var o = Enum.Parse(typeof (T), s);
            return (T)o;
        }
        catch(ArgumentException)
        {
            return null;
        }
    }
    
    static void Main(string[] args)
    {
       Console.WriteLine(ParseEnum("Enum11"));
       Console.WriteLine(ParseEnum("Enum1"));
       Console.WriteLine(ParseEnum("Enum6").GetType());
       Console.WriteLine(ParseEnum("Enum10"));
    }
    

    OUTPUT:

        //This line is empty as Enum11 is not there and function returns a null
    Enum1
    TestApp.Program+MyEnum
    Enum10
    Press any key to continue . . .
    

提交回复
热议问题