字符串在C#中枚举转换 [英] String to enum conversion in C#

查看:79
本文介绍了字符串在C#中枚举转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有我在哪里显示像一些条目的组合框:

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

Equals
Not Equals 
Less Than
Greater Than

请注意,这些字符串包含空格。我定义了一个枚举类型,像匹配这些条目:

Notice that these strings contain spaces. I have a enum defined which matches to these entries like:

enum Operation{Equals, Not_Equals, Less_Than, Greater_Than};

由于空间是不允许的,我已经使用_字符。

Since space is not allowed, I have used _ character.

现在,有没有什么办法,以给定的字符串自动转换为一个枚举元素,而无需编写循环或在C#中的一组,如果条件我自己的?

Now, is there any way to convert given string automatically to an enum element without writing a loop or a set of if conditions my self in C#?

推荐答案

我建议建立一个词典<字符串操作> 来映射友好的名称枚举常量和正常使用在命名元素本身约定。

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(' ', '_'));

这篇关于字符串在C#中枚举转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆