How to get enum value by string or int

后端 未结 10 1249
慢半拍i
慢半拍i 2020-12-07 12:43

How can I get the enum value if I have the enum string or enum int value. eg: If i have an enum as follows:

public enum TestEnum
{
    Value1 = 1,
    Value         


        
10条回答
  •  不思量自难忘°
    2020-12-07 13:24

    You could use following method to do that:

    public static Output GetEnumItem(Input input)
        {
            //Output type checking...
            if (typeof(Output).BaseType != typeof(Enum))
                throw new Exception("Exception message...");
    
            //Input type checking: string type
            if (typeof(Input) == typeof(string))
                return (Output)Enum.Parse(typeof(Output), (dynamic)input);
    
            //Input type checking: Integer type
            if (typeof(Input) == typeof(Int16) ||
                typeof(Input) == typeof(Int32) ||
                typeof(Input) == typeof(Int64))
    
                return (Output)(dynamic)input;
    
            throw new Exception("Exception message...");
        }
    

    Note:this method only is a sample and you can improve it.

提交回复
热议问题