将标记的枚举解析为列表的最有效的方式 [英] Most efficient way to parse a flagged enum to a list

查看:108
本文介绍了将标记的枚举解析为列表的最有效的方式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个标记的枚举,需要检索所有设置的值的名称。



我目前正在利用枚举的ToString()方法返回元素以逗号分隔。

  public void SetRoles(Enums.Roles role)
{
IList< Entities.Role> roleList = role.ToString(G)。Split(',')
.Select(r => new Entities.Role(r.Trim()))
.ToList();
...
}

我确定必须有更好的

解决方案

好的问题!



没有比以下更好的东西:

  public void SetRoles(Enums.Roles role)
{
列表< ;串GT; result = new List< string>();
foreach(Enum.GetValues(typeof(Roles))中的角色r
{
if((role& r)!= 0)result.Add(r.ToString());
}
}


I have a flagged enum and need to retrieve the names of all values set on it.

I am currently taking advantage of the enum's ToString() method which returns the elements comma-separated.

    public void SetRoles(Enums.Roles role)
    {
        IList<Entities.Role> roleList = role.ToString("G").Split(',')
            .Select(r => new Entities.Role(r.Trim()))
            .ToList();
    ...
    }

I'm sure there must be a better way than this.

解决方案

Good question!

I can't think of anything better than:

public void SetRoles(Enums.Roles role)
{
  List<string> result = new List<string>();
  foreach(Roles r in Enum.GetValues(typeof(Roles))
  {
    if ((role & r) != 0) result.Add(r.ToString());
  }
}

这篇关于将标记的枚举解析为列表的最有效的方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆