How to use generic Tryparse with Enum?

后端 未结 5 1321
时光说笑
时光说笑 2020-12-05 06:56

I\'m trying to build generic function that get from user string and try to parse it to Enum valuse like this:

private Enum getEnumStringEnumType(Type i_EnumT         


        
5条回答
  •  醉话见心
    2020-12-05 07:34

    You should make a generic method:

    private T getEnumStringEnumType() where T : struct, IConvertible
        {
            string userInputString = string.Empty;
            T resultInputType = default(T);
            bool enumParseResult = false;
    
            while (!enumParseResult)
            {
                userInputString = System.Console.ReadLine();
                enumParseResult = Enum.TryParse(userInputString, out resultInputType);
            }
    
            return resultInputType;
        }
    

    usage:

    public enum myEnum { val1, val2 }
    
    myEnum enumValue = getEnumStringEnumType();
    

提交回复
热议问题