String to enum conversion in C#

后端 未结 8 2097
孤街浪徒
孤街浪徒 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.

提交回复
热议问题