如何将 IEnumerable转换为C# 中的枚举?
我已将多个字符串解析为枚举标志,但看不到将它们合并为单个枚举位字段的巧妙方法。
我使用的方法循环遍历字符串值,然后 |= 将值转换为 Enum 对象,如下所示:
[Flags]
public enum MyEnum { None = 0, First = 1, Second = 2, Third = 4 }
...
string[] flags = { "First", "Third" };
MyEnum e = MyEnum.None;
foreach (string flag in flags)
e |= (MyEnum)Enum.Parse(typeof(MyEnum), flag, true);
我尝试使用 Select 方法转换为我的 Enum 类型,但后来我陷入了 IEnumerable
。有什么建议吗?
I've parsed several strings into Enum flags but can't see a neat way of merging them into a single Enum bitfield.
The method I'm using loops through the string values then |= the casted values to the Enum object, like so:
[Flags]
public enum MyEnum { None = 0, First = 1, Second = 2, Third = 4 }
...
string[] flags = { "First", "Third" };
MyEnum e = MyEnum.None;
foreach (string flag in flags)
e |= (MyEnum)Enum.Parse(typeof(MyEnum), flag, true);
I've tried using a Select method to convert to my Enum type, but then I'm stuck with IEnumerable<MyEnum>
. Any suggestions?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
好吧,在
IEnumerable
中,您可以使用:或者为了容纳空序列:
不可否认,它基本上与您已经得到的东西相同......
所以总的来说,代码将是:(
您可以根据 Guffa 的回答在单个
Aggregate
调用中执行它,但我个人认为为了清楚起见,我会将两者分开。不过,这是个人偏好。)请注意,我的 <一个href="http://code.google.com/p/unconstrained-melody/">Unconstrained Melody 项目使枚举处理更加愉快,您还可以使用通用的 .NET 4 中的
Enum.TryParse
方法。例如,使用 Unconstrained Melody 您可以使用:
Well, from an
IEnumerable<MyEnum>
you can use:or in order to accommodate an empty sequence:
It's basically the same thing as you've already got, admittedly...
So overall, the code would be:
(You can perform it in a single
Aggregate
call as per Guffa's answer, but personally I think I'd keep the two separate, for clarity. It's a personal preference though.)Note that my Unconstrained Melody project makes enum handling somewhat more pleasant, and you can also use the generic
Enum.TryParse
method in .NET 4.So for example, using Unconstrained Melody you could use:
您可以使用
Aggregate
方法将标志放在一起:You can use the
Aggregate
method to put the flags together: