如何将字符串转换为int类型的枚举?

发布于 2024-08-10 14:48:49 字数 388 浏览 3 评论 0原文

可能的重复:
如何将字符串转换为枚举C#?

我有一个 int 类型的枚举:

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

如果我有一个字符串:

string something = "blah1"

如何将其转换为 BlahType?

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

I have an enum of type int:

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

If I have a string:

string something = "blah1"

How can I convert this to BlahType?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

你怎么这么可爱啊 2024-08-17 14:48:49

我使用这样的函数

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

,你可以这样调用它

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

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");
献世佛 2024-08-17 14:48:49

您想要 Enum.Parse

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

You want Enum.Parse

BlahType blahValue = (BlahType) Enum.Parse(typeof(BlahType), something); 
〃温暖了心ぐ 2024-08-17 14:48:49

我使用这个函数将字符串转换为枚举;然后你可以转换为 int 或其他什么。

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);
}

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);
}
握住你手 2024-08-17 14:48:49
    public enum BlahType
    {
        blah1 = 1,
        blah2 = 2
    }

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

如果您不确定转换是否会成功 - 则使用 改为尝试解析

    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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文