String to enum conversion in C#

后端 未结 8 2093
孤街浪徒
孤街浪徒 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:32

    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(' ', '_'));
    
    0 讨论(0)
  • 2020-12-03 01:33

    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.

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