[英]How to format enum with flags attribute as hex value?
我嘗試使用枚舉ToString
方法顯示枚舉值。 枚舉具有Flags
屬性。
有些值與枚舉值的任何組合都不匹配。
在這種情況下, ToString
將數字作為十進制返回,但我想將其顯示為十六進制字符串。
使用ToString("X8")
將始終返回十六進制值。
我嘗試了Enum.IsDefined
,但它只對非組合值返回true。
例:
0x00000201 -> "XXt, TSW_AUTO_DETECT" (known values)
0x00010108 -> "00010108" (unknown value)
問:如何將未知枚舉值"ToString"
作為十六進制值?
您可以檢查該值是否設置了任何其他位而不是flags枚舉的總位掩碼。 如果是這樣,返回數字,否則正常的tostring:
public static string GetDescription(EnumName value)
{
var enumtotal = Enum.GetValues(typeof(EnumName)).Cast<int>().Aggregate((i1, i2) => i1 | i2); //this could be buffered for performance
if ((enumtotal | (int)value) == enumtotal)
return value.ToString();
return ((int)value).ToString("X8");
}
您需要編寫自己的字符串轉換例程,不能為枚舉重寫ToString()。 為了格式化[Flags],請查看System.Enum.InternalFlagsFormat:
private static String InternalFlagsFormat(RuntimeType eT, Object value)
{
Contract.Requires(eT != null);
Contract.Requires(value != null);
ulong result = ToUInt64(value);
HashEntry hashEntry = GetHashEntry(eT);
// These values are sorted by value. Don't change this
String[] names = hashEntry.names;
ulong[] values = hashEntry.values;
Contract.Assert(names.Length == values.Length);
int index = values.Length - 1;
StringBuilder retval = new StringBuilder();
bool firstTime = true;
ulong saveResult = result;
// We will not optimize this code further to keep it maintainable. There are some boundary checks that can be applied
// to minimize the comparsions required. This code works the same for the best/worst case. In general the number of
// items in an enum are sufficiently small and not worth the optimization.
while (index >= 0)
{
if ((index == 0) && (values[index] == 0))
break;
if ((result & values[index]) == values[index])
{
result -= values[index];
if (!firstTime)
retval.Insert(0, enumSeperator);
retval.Insert(0, names[index]);
firstTime = false;
}
index--;
}
// We were unable to represent this number as a bitwise or of valid flags
if (result != 0)
return value.ToString();
// For the case when we have zero
if (saveResult==0)
{
if (values.Length > 0 && values[0] == 0)
return names[0]; // Zero was one of the enum values.
else
return "0";
}
else
return retval.ToString(); // Return the string representation
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.