C#中的字符串枚举转换

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1187085/
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-06 10:19:54  来源:igfitidea点击:

String to enum conversion in C#

c#enums

提问by Naveen

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#?

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

采纳答案by Mehrdad Afshari

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

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

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(' ', '_'));

回答by Richard Szalay

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

使用字典创建专用映射器(根据 Mehrdad 的回答)或实现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.

您的自定义 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");
            }
        }
    }
}

This implementation could be improved in several ways:

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

回答by AdaTheDev

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(" ", "_"));

回答by Samuel Carrijo

You can use the Parse method:

您可以使用 Parse 方法:

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

Some examples here

这里有一些例子

回答by ablmf

Why use another way : convert Enumeration to String?

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

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

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

回答by VoidPointer

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

在 C# 中,您可以向枚举类型添加扩展方法。请参阅 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.

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

回答by arviman

I would use a singleton of this enum mapper classthat 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.

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

回答by A_Arnold

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

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

See herefor the documentation.

有关文档,请参见此处