我想獲得一個enum中每個值的值和屬性。
我知道我可以回圈使用這些值。
我知道我可以回圈使用這些值。
foreach (TEnum value in Enum. GetValues(typeof(TEnum)))
{
MemberInfo? info = value.GetType().GetMember(value.ToString()).FirstOrDefault() 。
if (info != null)
{
CustomAttribute? attribute = info.GetCustomAttribute<CustomAttribute>()。
if (attributee != null)
EnumLookup.Add(attribute.Code, value)
}
}
但是這似乎是非常低效的,必須為每一個值呼叫GetMember()和GetCustomAttribute()。
如果我使用GetMembers()或GetFields()來獲取所有列舉值的資訊,然后回圈瀏覽它們,這似乎會更有效率。
FieldInfo[]? fields = typeof(TEnum).GetFields(BindingFlags.Public | BindingFlags.Static) 。
foreach (FieldInfo field in fields)
{
CustomAttribute? attribute = field.GetCustomAttribute<CustomAttribute>()。
if (attributee != null)
EnumLookup.Add(code, /* Whoops! What to put here? */ ) 。
}
但是,我怎樣才能得到每個人的值呢?
列舉很奇怪,因為它的值就像靜態欄位,但是似乎沒有辦法通過反射獲得靜態欄位的值。
注意: uj5u.com熱心網友回復: 我建議你有某種存盤,讓我們稱之為 之后,你暴露了一個方法 所以這段代碼只在運行時通過掃描你的程式集完成一次,之后代碼的消費者,他們需要做的就是呼叫你的 所以我們的想法基本上是,由于你的大部分作業實際上是靜態的,你可以在運行時只做一次。但是如果你需要比更高的效率,你就必須在更低的層次上進行處理,例如 或者更好的是,根據你最后的評論,你似乎并不關心列舉的單個值,你將需要某些列舉型別的所有值,而且你并不關心順序。你可以很容易地在一個字典中映射,例如 uj5u.com熱心網友回復: 因此,我發現列舉值的行為類似于靜態欄位。所以我可以列舉我的列舉型別的欄位。要獲得一個靜態欄位的值,你只需將 這使我不必在回圈中每次都呼叫 不幸的是,在啟用
標籤:EnumLookup是一個字典,它將一個代碼(存盤在CustomAttribute中)映射到列舉值。
EnumsAttributesStore,它在運行時只掃描你的程式集,對于每個列舉型別T,它呼叫它Enum.GetValues,然后它得到該列舉成員的自定義屬性。
ResolveMemberValue<TEnum>(string memberName),所有EnumsAttributesStore需要做的只是查找某種哈希表IDictionary<TEnum, (Attribute customAttribute, object value) 。
ResolveMemberValue或任何你想呼叫的東西來獲取屬性,甚至可能是從列舉值中獲取值。
IL。
IDictionary<EnumType, IDictionary<string,string>>。你輸入列舉的型別,然后你收到一個哈希圖,其中鍵是各個列舉的名稱,值是屬性的值,所有這些都只在運行時的匯編加載中完成一次。
null傳遞給FieldInfo.GetValue()。
GetMember()。FieldInfo[] fieldsInfo = typeof(TEnum).GetFields(BindingFlags.Public | BindingFlags.Static) 。
foreach (FieldInfo fieldInfo in fieldsInfo)
{
CustomAttribute? attribute = fieldInfo.GetCustomAttribute<CustomAttribute>()。
if (attributee != null)
EnumLookup.Add(attribute.Code, (TEnum)fieldInfo.GetValue(null))。
}
nullable的情況下,它給了我一個警告,即欄位值可能為空,盡管它不能。接下來將解決這個問題。
