Int数组到Flags Enum

时间:2014-03-01 23:41:36

标签: c#

我有以下枚举:

[Flags]
public enum RoleModel {
  Admin = 1 << 0,
  Editor = 1 << 1,
  Member = 1 << 2
}

我有一个整数列表:

List<int> = new List<int> { 1, 3 }

如何将Ints解析为标志枚举?

谢谢你, 米格尔

2 个答案:

答案 0 :(得分:0)

你只需要做一个演员:

RoleModel x = (RoleModel)1;
Debug.Assert(x.HasFlag(RoleModel.Admin));

RoleModel y = (RoleModel)3;
Debug.Assert(y.HasFlag(RoleModel.Editor) && y.HasFlag(RoleModel.Member));

答案 1 :(得分:0)

使用LINQ的解决方案:

List<int> list = new List<int> { 1, 3 };

List<RoleModel> parsedList = 
    list.Select(n => Enum.GetName(typeof(RoleModel), n) ?? String.Empty)
        .Where(s => !String.IsNullOrEmpty(s))
        .Select(s => (RoleModel)Enum.Parse(typeof(RoleModel), s))
        .ToList();