从标志枚举中列出所有位名称 [英] List all bit names from a flag 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< HWResponse>
包含 {Ready,Error} code>。
I feed it 0x81, and it should provide me with a IEnumerable<HWResponse>
containing {Ready, Error}
.
由于我没有找到更简单的方法,我试图在下面编写代码,但是我无法编译它。 p>
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
但枚举是一种特殊类型,禁止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>();
}
这篇关于从标志枚举中列出所有位名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!