How to use generic Tryparse with Enum?

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

    Long ago in Visual Studio 2005 era, I made my own method for TryParse on Enum. I only recently discovered the 2008 implementation and I'm not happy with it's restrictiveness, especially considering that it's a TRY PARSE method; meaning that a programmer is testing an input!

    Generally, I prefer to use methods which trust the programmer to know what he's doing :)

    My implementation is as follows:

    public static bool EnumTryParse(string input, out T theEnum)
    {
        foreach (string en in Enum.GetNames(typeof(T)))
        {
            if (en.Equals(input, StringComparison.CurrentCultureIgnoreCase))
            {
                theEnum = (T)Enum.Parse(typeof(T), input, true);
                return true;
            }
        }
    
        theEnum = default(T);
        return false;
    }
    

    The lack of a where T:struct puts the trust in the developer's hands, but it allows you to compile with unknown, generic enums.

    As an alternative, you can create a method looping on Enum.GetValues if you want to do an integer comparison when converting to your specified enum.

    Hope this helps.

提交回复
热议问题