列出标志 Enum 中的所有位名称 [英] List all bit names from a flag Enum

查看:24
本文介绍了列出标志 Enum 中的所有位名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个帮助方法来列出 Enum 值中设置的所有位的名称(用于记录目的).我想要一个方法来返回在某些变量中设置的所有 Enum 值的列表.在我的例子中

I'm trying to make a helper method for listing the names of all bits set in an Enum value (for logging purposes). I want have a method that would return the list of all the Enum values set in some variables. In my example

[Flag]
Enum HWResponse
{
   None = 0x0,
   Ready = 0x1,
   Working = 0x2,
   Error = 0x80,
}

我给它 0x81,它应该为我提供一个 IEnumerable 包含 {Ready, Error}.

I feed it 0x81, and it should provide me with a IEnumerable<HWResponse> containing {Ready, Error}.

由于没有找到更简单的方法,我尝试编写下面的代码,但无法编译.

As I didn't find a simpler way, I tried to write the code below, but I can't make it compile.

public static IEnumerable<T> MaskToList<T>(Enum mask) 
{
  if (typeof(T).IsSubclassOf(typeof(Enum)) == false)
    throw new ArgumentException();

  List<T> toreturn = new List<T>(100);

  foreach(T curValueBit in Enum.GetValues(typeof (T)).Cast<T>())
  {
    Enum bit = ((Enum) curValueBit);  // Here is the error

    if (mask.HasFlag(bit))
      toreturn.Add(curValueBit);
  }

  return toreturn;
}

在此版本的代码中,编译器抱怨它无法将 T 强制转换为 Enum.

On this version of the code, the compiler complains that it can't cast T to Enum.

我做错了什么?有没有更好(更简单)的方法来做到这一点?我怎样才能制作演员表?

What did I do wrong? Is there a better (simpler) way to do this? How could I make the cast?

另外,我试着把方法写成

Also, I tried to write the method as

public static IEnumerable<T> MaskToList<T>(Enum mask) where T:Enum

但是 Enum 是一种特殊类型,它禁止使用where"语法(使用 C# 4.0)

but Enum is of a special type that forbids the 'where' syntax (Using C# 4.0)

推荐答案

这是使用 LINQ 编写它的简单方法:

Here's a simple way to write it using LINQ:

public static IEnumerable<T> MaskToList<T>(Enum mask)
{
    if (typeof(T).IsSubclassOf(typeof(Enum)) == false)
        throw new ArgumentException();

    return Enum.GetValues(typeof(T))
                         .Cast<Enum>()
                         .Where(m => mask.HasFlag(m))
                         .Cast<T>();
}

这篇关于列出标志 Enum 中的所有位名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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