C# 中字符串到枚举的转换

发布于 2024-07-29 08:09:56 字数 321 浏览 6 评论 0原文

我有一个组合框,其中显示一些条目,例如:

Equals
Not Equals 
Less Than
Greater Than

请注意,这些字符串包含空格。 我定义了一个与这些条目匹配的枚举,例如:

enum Operation{Equals, Not_Equals, Less_Than, Greater_Than};

由于不允许使用空格,因此我使用了 _ 字符。

现在,有没有什么方法可以将给定字符串自动转换为枚举元素,而无需在 C# 中编写循环或一组 if 条件?

I have a combo box where I am displaying some entries like:

Equals
Not Equals 
Less Than
Greater Than

Notice that these strings contain spaces. I have a enum defined which matches to these entries like:

enum Operation{Equals, Not_Equals, Less_Than, Greater_Than};

Since space is not allowed, I have used _ character.

Now, is there any way to convert given string automatically to an enum element without writing a loop or a set of if conditions my self in C#?

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

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

发布评论

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

评论(8

丢了幸福的猪 2024-08-05 08:09:56

我建议构建一个 Dictionary 将友好名称映射到枚举常量,并在元素本身中使用正常的命名约定。

enum Operation{ Equals, NotEquals, LessThan, GreaterThan };

var dict = new Dictionary<string, Operation> {
    { "Equals", Operation.Equals },
    { "Not Equals", Operation.NotEquals },
    { "Less Than", Operation.LessThan },
    { "Greater Than", Operation.GreaterThan }
};

var op = dict[str]; 

或者,如果您想坚持当前的方法,您可以这样做(我建议不要这样做):

var op = (Operation)Enum.Parse(typeof(Operation), str.Replace(' ', '_'));

I suggest building a Dictionary<string, Operation> to map friendly names to enum constants and use normal naming conventions in the elements themselves.

enum Operation{ Equals, NotEquals, LessThan, GreaterThan };

var dict = new Dictionary<string, Operation> {
    { "Equals", Operation.Equals },
    { "Not Equals", Operation.NotEquals },
    { "Less Than", Operation.LessThan },
    { "Greater Than", Operation.GreaterThan }
};

var op = dict[str]; 

Alternatively, if you want to stick to your current method, you can do (which I recommend against doing):

var op = (Operation)Enum.Parse(typeof(Operation), str.Replace(' ', '_'));
ぶ宁プ宁ぶ 2024-08-05 08:09:56
Operation enumVal = (Operation)Enum.Parse(typeof(Operation), "Equals")

对于“不等于”,您显然需要在上述语句中将空格替换为下划线

编辑:以下版本在尝试解析之前将空格替换为下划线:

string someInputText;
var operation = (Operation)Enum.Parse(typeof(Operation), someInputText.Replace(" ", "_"));
Operation enumVal = (Operation)Enum.Parse(typeof(Operation), "Equals")

For "Not Equals", you obv need to replace spaces with underscores in the above statement

EDIT: The following version replaces the spaces with underscores before attempting the parsing:

string someInputText;
var operation = (Operation)Enum.Parse(typeof(Operation), someInputText.Replace(" ", "_"));
静水深流 2024-08-05 08:09:56

使用字典创建专用映射器(根据 Mehrdad 的答案)或实现 类型转换器

您的自定义 TypeConverter 可以替换 " " -> “_”(反之亦然),或者它可以反映枚举并使用属性来确定项目的显示文本。

enum Operation
{
    [DisplayName("Equals")]
    Equals, 

    [DisplayName("Not Equals")]
    Not_Equals, 

    [DisplayName("Less Than")]
    Less_Than, 

    [DisplayName("Greater Than")]
    Greater_Than
};

public class OperationTypeConverter : TypeConverter
{
    private static Dictionary<string, Operation> operationMap;

    static OperationTypeConverter()
    {
        BindingFlags bindingFlags = BindingFlags.Static | BindingFlags.GetField
            | BindingFlags.Public;

        operationMap = enumType.GetFields(bindingFlags).ToDictionary(
            c => GetDisplayName(c)
            );
    }

    private static string GetDisplayName(FieldInfo field, Type enumType)
    {
        DisplayNameAttribute attr = (DisplayNameAttribute)Attribute.GetCustomAttribute(typeof(DisplayNameAttribute));

        return (attr != null) ? attr.DisplayName : field.Name;
    }

    public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
    {
        string stringValue = value as string;

        if (stringValue != null)
        {
            Operation operation;
            if (operationMap.TryGetValue(stringValue, out operation))
            {
                return operation;
            }
            else
            {
                throw new ArgumentException("Cannot convert '" + stringValue + "' to Operation");
            }
        }
    }
}

可以通过多种方式改进此实现:

Either create a dedicated mapper using a dictionary (per Mehrdad's answer) or implement a TypeConverter.

Your custom TypeConverter could either replace " " -> "_" (and vice versa) or it could reflect the enumeration and use an attribute for determining the display text of the item.

enum Operation
{
    [DisplayName("Equals")]
    Equals, 

    [DisplayName("Not Equals")]
    Not_Equals, 

    [DisplayName("Less Than")]
    Less_Than, 

    [DisplayName("Greater Than")]
    Greater_Than
};

public class OperationTypeConverter : TypeConverter
{
    private static Dictionary<string, Operation> operationMap;

    static OperationTypeConverter()
    {
        BindingFlags bindingFlags = BindingFlags.Static | BindingFlags.GetField
            | BindingFlags.Public;

        operationMap = enumType.GetFields(bindingFlags).ToDictionary(
            c => GetDisplayName(c)
            );
    }

    private static string GetDisplayName(FieldInfo field, Type enumType)
    {
        DisplayNameAttribute attr = (DisplayNameAttribute)Attribute.GetCustomAttribute(typeof(DisplayNameAttribute));

        return (attr != null) ? attr.DisplayName : field.Name;
    }

    public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
    {
        string stringValue = value as string;

        if (stringValue != null)
        {
            Operation operation;
            if (operationMap.TryGetValue(stringValue, out operation))
            {
                return operation;
            }
            else
            {
                throw new ArgumentException("Cannot convert '" + stringValue + "' to Operation");
            }
        }
    }
}

This implementation could be improved in several ways:

土豪我们做朋友吧 2024-08-05 08:09:56

您可以使用 Parse 方法:

 Operarion operation = (Operation)Enum.Parse(typeof(Operation), "Not_Equals");

一些示例 此处

You can use the Parse method:

 Operarion operation = (Operation)Enum.Parse(typeof(Operation), "Not_Equals");

Some examples here

淡笑忘祈一世凡恋 2024-08-05 08:09:56

为什么使用另一种方式:将枚举转换为字符串?

只需从枚举生成组合框的项目即可。

Why use another way : convert Enumeration to String?

Just generate the items of your combo box from your Enumeration.

权谋诡计 2024-08-05 08:09:56

在 C# 中,您可以向枚举类型添加扩展方法。 看
http://msdn.microsoft.com/en-us/library/bb383974。 aspx

您可以使用此方法将 toString(Operation op)、fromString(String str) 和 toLocalizedString(Operation op) 方法添加到枚举类型中。 用于查找特定字符串的方法取决于您的应用程序,并且应该与您在类似情况下执行的操作一致。 只要您的应用程序不需要完全本地化,按照其他人的建议使用字典似乎是一个不错的第一种方法。

in C#, you can add extension methods to enum types. See
http://msdn.microsoft.com/en-us/library/bb383974.aspx

You could use this approach to add toString(Operation op), fromString(String str) and toLocalizedString(Operation op) methods to your enum types. The method that you use to lookup the particular string depends on your application and should be consistent with what you do in similar cases. Using a dictionary as others have suggested seems like a good first approach as long as you don't need full localization in your app.

傲世九天 2024-08-05 08:09:56

我会使用这个 enum 映射器类 的单例,它的执行速度比 Enum.Parse (它使用反射并且速度非常慢)。
然后,您可以使用 EnumFromString(typeof(YourEnum), "stringValue") 来获取枚举。

I would use a singleton of this enum mapper class that performs much faster than Enum.Parse (which uses reflection and is really slow).
You can then use EnumFromString(typeof(YourEnum), "stringValue") to get your enum.

旧时模样 2024-08-05 08:09:56

从 C# 8 开始,您可以使用开关来做到这一点。 在你的例子中,我相信代码会是这样的。

enum Operation{Equals, Not_Equals, Less_Than, Greater_Than};

public static string OperationString(Operation opString) =>
    opString switch
    {
        Operation.Equals => "Equals",
        Operation.Not_Equals => "Not Equals",
        Operation.Less_Than=> "Less Than",
        Operation.Greater_Than=> "Greater Than",
        _   => throw new ArgumentException(message: "invalid enum value", paramName: nameof(opString )),
    };

有关文档。

As of C# 8 you can do that using switches. In your example I believe the code would be like this.

enum Operation{Equals, Not_Equals, Less_Than, Greater_Than};

public static string OperationString(Operation opString) =>
    opString switch
    {
        Operation.Equals => "Equals",
        Operation.Not_Equals => "Not Equals",
        Operation.Less_Than=> "Less Than",
        Operation.Greater_Than=> "Greater Than",
        _   => throw new ArgumentException(message: "invalid enum value", paramName: nameof(opString )),
    };

See here for the documentation.

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