如何通过迭代枚举来设置枚举实例[复制](how to set an enum instance by iterating through an enum [duplicate])

编程入门 行业动态 更新时间:2024-10-06 15:31:33
如何通过迭代枚举来设置枚举实例[复制](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 answers

Not 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); } }

更多推荐

本文发布于:2023-08-04 03:36:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1408595.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:实例   迭代   set   enum   iterating

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!