String to enum conversion in C#

后端 未结 8 2112
孤街浪徒
孤街浪徒 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 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 {
        { "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(' ', '_'));
    

提交回复
热议问题