有没有更好的方法来创建枚举方法或枚举扩展的通用转换字符串?

Kel*_*sey 5 c# extension-methods enums

我在枚举助手类中有以下方法(我为了问题的目的简化了它):

static class EnumHelper
{
    public enum EnumType1 : int
    {
        Unknown = 0,
        Yes = 1,
        No = 2
    }

    public enum EnumType2 : int
    {
        Unknown = 0,
        Dog = 1,
        Cat = 2,
        Bird = 3
    }

    public enum EnumType3
    {
        Unknown,
        iPhone,
        Andriod,
        WindowsPhone7,
        Palm
    }

    public static EnumType1 ConvertToEnumType1(string value)
    {
        return (string.IsNullOrEmpty(value)) ?
            EnumType1.Unknown :
            (EnumType1)(Enum.Parse(typeof(EnumType1), value, true));
    }

    public static EnumType2 ConvertToEnumType2(string value)
    {
        return (string.IsNullOrEmpty(value)) ?
            EnumType2.Unknown :
            (EnumType2)(Enum.Parse(typeof(EnumType2), value, true));
    }

    public static EnumType3 ConvertToEnumType3(string value)
    {
        return (string.IsNullOrEmpty(value)) ?
            EnumType3.Unknown :
            (EnumType3)(Enum.Parse(typeof(EnumType3), value, true));
    }
}
Run Code Online (Sandbox Code Playgroud)

所以这里的问题是,我可以将其修改为Enum扩展方法,或者可以处理任何类型的某种类型的单一方法.我已经找到了一些使用基本枚举的例子,但我的例子中的不同之处在于Unknown,如果字符串为null或为空(如果找不到匹配项,我希望它失败),所有枚举都需要返回我需要的项.

寻找类似以下的东西:

EnumType1 value = EnumType1.Convert("Yes");
// or
EnumType1 value = EnumHelper.Convert(EnumType1, "Yes");
Run Code Online (Sandbox Code Playgroud)

完成所有工作的一个功能......如何处理Unknown元素是我挂断的部分.

编辑:调整其中一个枚举不用整数定义.所以我可以保证0总是如此,但Unknown总是正确的文本...我想我可以使用与T(0)相同的例子,但对文本"Unknown"做另一个解析.

chi*_*emp 8

假设Unknown始终为0值,请使用此选项.

public static T ConvertToEnum<T>(this string value) where T : new()
{
    if( !typeof(T).IsEnum )
        throw new NotSupportedException( "T must be an Enum" );

    try
    {
        return (T)Enum.Parse(typeof(T), value);
    }
    catch
    {
        return default(T); // equivalent to (T)0
        //return (T)Enum.Parse(typeof(T), "Unknown"));
    }
}
Run Code Online (Sandbox Code Playgroud)

用法:

EnumType2 a = "Cat".ConvertToEnum<EnumType2>(); 
EnumType2 b = "Person".ConvertToEnum<EnumType2>(); // Unknown
Run Code Online (Sandbox Code Playgroud)

编辑OP(Kelsey):你的答案引导我得到正确的答案,所以我想我会把它包括在这里:

public static T ConvertTo<T>(this string value)
{
    T returnValue = (T)(Enum.Parse(typeof(T), "Unknown", true));
    if ((string.IsNullOrEmpty(value) == false) && 
        (typeof(T).IsEnum))
    {
        try { returnValue = (T)(Enum.Parse(typeof(T), value, true)); }
        catch { }
    }
    return returnValue;
}
Run Code Online (Sandbox Code Playgroud)