String to enum conversion in C#

后端 未结 8 2092
孤街浪徒
孤街浪徒 2020-12-03 00:52

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

Equals
Not Equals 
Less Than
Greater Than

Notice that these strings contain spa

相关标签:
8条回答
  • 2020-12-03 01:06

    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.

    0 讨论(0)
  • 2020-12-03 01:11

    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.

    0 讨论(0)
  • 2020-12-03 01:12

    You can use the Parse method:

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

    Some examples here

    0 讨论(0)
  • 2020-12-03 01:14

    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:

    • Make it generic
    • Implement ConvertTo
    • Support FlagsAttribute
    0 讨论(0)
  • 2020-12-03 01:22
    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(" ", "_"));
    
    0 讨论(0)
  • 2020-12-03 01:28

    Why use another way : convert Enumeration to String?

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

    0 讨论(0)
提交回复
热议问题