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

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

问题描述

 等于
不等于
小于
大于

请注意,这些字符串包含空格。我有一个枚举与这些条目匹配,如:

 枚举操作{Equals,Not_Equals,Less_Than,Greater_Than}; 

由于空间不允许,我使用_字符。



现在,有没有办法将给定的字符串自动转换为枚举元素,而无需编写循环或一组if(C)条件我的自我?

解决方案

我建议建立一个 Dictionary< string,Operation> 将友好名称映射到枚举常量,并在元素本身中使用正常的命名约定。

 枚举操作{Equals,NotEquals,LessThan,GreaterThan}; 

var dict = new Dictionary< string,Operation> {
{Equals,Operation.Equals},
{Not Equals,Operation.NotEquals},
{Less thanan,Operation.LessThan},
{ 大于,Operation.GreaterThan}
};

var op = dict [str];

或者,如果你想坚持你现在的方法,你可以做(​​我建议反对做):

  var op =(Operation)Enum.Parse(typeof(Operation),str.Replace('','_ )); 


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.

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天全站免登陆