我试图制作一个帮助方法来列出在枚举值中设置的所有位的名称(用于记录目的).我想有一个方法可以返回在一些变量中设置的所有枚举值的列表.在我的例子中
[Flag]
Enum HWResponse
{
None = 0x0,Ready = 0x1,Working = 0x2,Error = 0x80,}
我给它0x81,它应该提供一个IEnumerable< HWResponse>包含{Ready,Error}.
因为我没有找到一个更简单的方法,我试图写下面的代码,但我不能编译.
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.
我做错了什么?有没有更好(更简单)的方法来做到这一点?我该怎么做演员?
另外,我试图把方法写成
public static IEnumerable<T> MaskToList<T>(Enum mask) where T:Enum
但是Enum是一种特殊类型,禁止’where’语法(使用C#4.0)
解决方法
这是一个使用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>();
}