如何通过迭代枚举来设置枚举实例[复制](how to set an enum instance by iterating through an enum [duplicate])
这个问题在这里已经有了答案:
如何通过字符串或int 8的答案 获得枚举值 如何从C#中的字符串中获取枚举值? 6个答案不知道如何用文字表达我想要的。 我需要设置一个给定输入的枚举类型。 示例代码如下:
Class Foo{ enum Color{ BLUE, RED, YELLOW } public Color color; public setColor(string col){ var colorsEnum = Enum.GetNames(typeof(Color)); foreach(var c in colorsEnum){ if(c == col) color = c.getEnum(); } } }This question already has an answer here:
How to get enum value by string or int 9 answers How to get a enum value from string in C#? 6 answersNot sure how to express by word what I want. I need to set an enum type given an input. Example code follows:
Class Foo{ enum Color{ BLUE, RED, YELLOW } public Color color; public setColor(string col){ var colorsEnum = Enum.GetNames(typeof(Color)); foreach(var c in colorsEnum){ if(c == col) color = c.getEnum(); } } }最满意答案
您甚至不需要遍历名称,为什么不使用Contains呢?
这里的技巧是使用Enum.Parse 。 在检查颜色有效后,只需调用Enum.Parse :
public void setColor(string col){ if (Enum.GetNames(typeof(Color)).Contains(col)) { color = (Color)Enum.Parse(typeof(Color), col); } }You don't need to even loop through the names, why not just use Contains?
The trick here is to use Enum.Parse. Just stick a call to Enum.Parse after you checked that the color is valid:
public void setColor(string col){ if (Enum.GetNames(typeof(Color)).Contains(col)) { color = (Color)Enum.Parse(typeof(Color), col); } }更多推荐
发布评论