开发者

How to conver a string to a enum of type int? [duplicate]

This question already has answers here: Closed 11 years ago.

Possible Duplicate:

How do I Convert a string to an enum in C#?

I have an enum of type int:

public enum Bla开发者_C百科hType
{
       blah1 = 1,
       blah2 = 2
}

If I have a string:

string something = "blah1"

How can I convert this to BlahType?


I use a function like this one

public static T GetEnumValue<T>(string value)
{
    return (T)Enum.Parse(typeof(T), value);
}

And you can call it like this

BlahType value = GetEnumValue<BlahType>("Blah1");


You want Enum.Parse

BlahType blahValue = (BlahType) Enum.Parse(typeof(BlahType), something); 


I use this function to convert a string to a enum; then you can cast to int or whatever.

public static T ToEnum<T>(string value, bool ignoreUpperCase)
        where T : struct, IComparable, IConvertible, IFormattable {
        Type enumType = typeof (T);
        if (!enumType.IsEnum) {
            throw new InvalidOperationException();
        }
        return (T) Enum.Parse(enumType, value, ignoreUpperCase);
}


    public enum BlahType
    {
        blah1 = 1,
        blah2 = 2
    }

    string something = "blah1";
    BlahType blah = (BlahType)Enum.Parse(typeof(BlahType), something);

If you are not certain that the conversion will succeed - then use TryParse instead.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜