开发者

Generic Method Enum To String Conversion

I have seen lots of method to convert a string to an enum using generics but cannot find a neat way to convert an enum to string using generics.

What I mean is Pass an enum and a value and return the mapped name开发者_Python百科 of the enum.

Any suggestions


How about:

enum E
{
    A = 2,
    B = 3
}

public static string GetLiteral<T>(object value)
{
    return Enum.GetName(typeof(T), value);
}

static void Main(string[] args)
{
    Console.WriteLine(GetLiteral<E>(2));
    Console.WriteLine(GetLiteral<E>(3));
}


This works when you know the value, and type of the enum but you want to get the enum instance back that is matching value..

    static T ConvertToEnum<T>(object value)
    {
        return (T) Enum.Parse(typeof(T), Enum.GetName(typeof(T), value));             
    }


    static void Main(string[] args)        
    {             
        Gender g1 = ConvertToEnum<Gender>(0); //Male
        Gender g2 = ConvertToEnum<Gender>(1); //Female
        Gender g3 = ConvertToEnum<Gender>(2); //*BANG* exception             
    }


I would write a extension method to do so eg

using System.ComponentModel;

public enum StatusResult
{
    [Description("Success")]
    Success,
    [Description("Failure...")]
    Failure
}

public static class AttributesHelperExtension
{
    public static string ToDescription(this Enum value)
    {
        DescriptionAttribute[] da = (DescriptionAttribute[])(value.GetType().GetField(value.ToString())).GetCustomAttributes(typeof(DescriptionAttribute), false);
        return da.Length > 0 ? da[0].Description : value.ToString();
    }

    public static T ToEnum<T>(this string stringValue, T defaultValue)
    {
        foreach (T enumValue in Enum.GetValues(typeof(T)))
        {
            DescriptionAttribute[] da = (DescriptionAttribute[])(typeof(T).GetField(enumValue.ToString())).GetCustomAttributes(typeof(DescriptionAttribute), false);
            if (da.Length > 0 && da[0].Description == stringValue)
                return enumValue;
        }
        return defaultValue;
    }
}

Now to call this use

string value = StatusResult.Failure.ToDescription();


I came across this method that I used to use a while ago.

It uses the Extensions, and should always return an enum

    public static T ToEnum<T>(this string type, T defaultEnum) 
    {
        T holder;
        try
        {
            holder = (T)Enum.Parse(typeof(T), type);
        }
        catch 
        {
            holder = defaultEnum;
        }
        return holder;
    }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜