我在類似於以下遍歷具有僅單個比特字段按位枚舉值
[Flags]
public enum Colors
{
None = 0,
Red = 1,
Green = 2,
Blue = 4,
Purple = Red | Blue,
Brown = Red | Green,
}
下面的代碼的代碼定義多個標誌枚舉產生以下輸出
Colors color1 = Colors.Red | Colors.Blue;
Colors color2 = Colors.Purple;
string s1 = color1.ToString(); // Sets s1 to "Purple"
string s2 = color2.ToString(); // Sets s2 to "Purple"
我想要一種方法來輸出按位枚舉的各個位,即使定義了匹配組合。
private void Foo()
{
Colors color1 = Colors.Red | Colors.Blue;
Colors color2 = Colors.Purple;
string s1 = CreateColumnString(color1); // Sets s1 to "Red|Blue"
string s2 = CreateColumnString(color2); // Sets s2 to "Red|Blue"
}
我以爲我可以遍歷枚舉的所有值,並檢查值是兩個冪。但我無法弄清楚如何獲得Enum參數的基礎價值。
private string CreateColumnString(object value)
{
//is this an enum with Flags attribute?
if (value is Enum && value.GetType().GetCustomAttributes(typeof(FlagsAttribute), true).Length > 0)
{
Enum e = (Enum)value;
//Get a list of Enum values set in this flags enum
IEnumerable<Enum> setValues =
Enum.GetValues(value.GetType())
.Cast<Enum>()
.Where(eachEnum => IsPowerOfTwo(eachEnum) && value.HasFlag(eachEnum));
return string.Join("|", setValues);
}
else
{
return value != null ? value.ToString() : string.Empty;
}
return str;
}
private static bool IsPowerOfTwo(Enum e)
{
int x = (int)e; //ERROR cannot convert type 'System.Enum' to 'ulong'
return (x != 0) && ((x & (x - 1)) == 0);
}
關於編輯的'IsPowerOfTwo'方法:考慮使用'Convert.ToInt32(e)'。在C#/ .NET中使用泛型枚舉非常難看。 –
難道你不能施展它嗎? http://stackoverflow.com/questions/943398/enums-returning-int-value – Minthos
沒關係,顯然你不能。 – Minthos