收录日期:2021/02/27 20:34:38 时间:2009-03-14 01:32:35 标签:c#

I'd like to have a simple helper method for converting a string to an Enum. Something like the following, but it doesn't like T as the first argument in the Enum.Parse. The error is T is a Type Parameter but is used like a variable.

public static T StringToEnum<T>(String value)
        {
            return (T) Enum.Parse(T,value,true) ;
        }

Try this:

public static T StringToEnum<T>(String value)
{
     return (T)Enum.Parse(typeof(T), value, true);
}
public static T StringToEnum<T>(String value)
{
    return (T) Enum.Parse(typeof(T),value,true) ;
}

What you were doing is like using 'int' as a Type, but it is not a Type object. To get the Type object, you would use typeof(int).

Here is a method extension I use.

/// <summary>
/// Will parse and string value and return the Enum given.  Case is ignored when doing the parse.
/// </summary>
/// <param name="typeOfEnum">The type of the Enum to Parse</param>
/// <param name="value">The string value for the result of the Enum</param>
/// <param name="errorValue">If an error is encountered this value is returned.  (For example could be an Enum)</param>
/// <returns>Returns Enum Object</returns>
public static T ToEnum<T>(this string value)
{
    return (T)Enum.Parse(typeof(T), value, true);
}