How to use generic Tryparse with Enum?

后端 未结 5 1315
时光说笑
时光说笑 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:37

    The TryParse method has the following signature:

    TryParse(string value, bool ignoreCase, out TEnum result)
        where TEnum : struct
    

    It has a generic type parameter TEnum that must be a struct and that is used to determine the type of enumeration being parsed. When you don't provide it explicitly (as you did), it will take the type of whatever you provide as the result argument, which in your case is of type Enum (and not the type of the enumeration itself).

    Note that Enum is a class (despite it inheriting from ValueType) and therefore it does not satisfy the requirement that TEnum is a struct.

    You can solve this by removing the Type parameter and giving the method a generic type parameter with the same constraints (i.e. struct) as the generic type parameter on the TryParse function.

    So try this, where I've named the generic type parameter TEnum:

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

    To call the method, use:

    GetEnumStringEnumType();
    

提交回复
热议问题