C# 如何从值的类型和名称创建枚举对象?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/169116/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-03 16:28:54  来源:igfitidea点击:

How to create enum object from its type and name of the value?

c#enums

提问by

I have a type (System.Type) of an enum and a string containing enumeration value to set.

我有一个枚举类型 (System.Type) 和一个包含要设置的枚举值的字符串。

E.g. given:

例如给出:

enum MyEnum { A, B, C };

I have typeof(MyEnum) and "B".

我有 typeof(MyEnum) 和“B”。

How do I create MyEnum object set to MyEnum.B?

如何创建设置为 MyEnum.B 的 MyEnum 对象?

回答by Yuval

MyEnum enumValue = (MyEnum)Enum.Parse(typeof(MyEnum), "B");

You also have a case-insensitive overload.

您还有一个不区分大小写的重载。

回答by Pavel Chuchuva

I assume you don't have access to MyEnum, only to typeof(MyEnum):

我假设您无权访问 MyEnum,只能访问 typeof(MyEnum):

void foo(Type t)
{
   Object o = Enum.Parse(t, "B");
}

回答by Brad Patton

You can do this with generics. I created a Utility class to wrap this:

你可以用泛型来做到这一点。我创建了一个 Utility 类来包装它:

public static class Utils {
    public static T ParseEnum<T>(string value) {
        return (T)Enum.Parse(typeof(T), value, true);
    }

Then invoked like:

然后像这样调用:

string s = "B";
MyEnum enumValue = Utils.ParseEnum<MyEnum>(s);