String to enum conversion in C#

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

提交回复
热议问题