[英]Is there a way to convert from a list of strings to an enum flag in c#?
我在xml文档中有一个字符串列表:
<properties>red yellow blue</properties>
我有一个枚举:
[Flags]
public enum Properties
{
None = 0,
red = 1,
yellow = 2,
blue = 4,
green = 8
}
有没有一种方法可以将XML字符串转换为枚举标志值7
或0111
?
与此相反,周围有无数资源,但是我很难找到有关从字符串转换为Flags的任何信息。
是的,但是您需要将它们用逗号分隔:
[Flags]
public enum Test
{
A = 1,
B = 2,
C = 4
}
Test t;
Enum.TryParse<Test>("A,B", out t);
由于名称中不能包含空格,因此您可以在调用TryParse之前将字符串替换为逗号。
当然
string flags = "red yellow blue";
var eflags = flags.Split()
.Select(s => (Properties)Enum.Parse(typeof(Properties), s))
.Aggregate((a, e) => a | e);
Console.WriteLine(eflags);
Console.WriteLine((int)eflags);
Outpus
红色,黄色,蓝色
7
我将把如何从xml中获取字符串的工作留给您。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.