[英]How to pass a generic Enum as dictionary key in method parameter
我試圖創建一種方法來計算給定枚舉在某些現有詞典中出現的次數,以進行報告:
private static Dictionary<string, int> CountEnumOccurrence(Dictionary<Enum, List<string>> valueSource)
{
var convertedDictionary = new Dictionary<string, int>();
foreach (var entry in valueSource)
{
var name = Enum.GetName(entry.Key.GetType(), entry.Key);
convertedDictionary.Add(name, entry.Value.Count);
}
return convertedDictionary;
}
但是,如果我嘗試這樣調用此方法:
var criticalFailureCounts = CountEnumOccurrence(reportSpan.criticalFailures));
我懂了
“無法從'
System.Collections.Generic.Dictionary<Reporter.CriticalFailureCategory,System.Collections.Generic.List<string>>
'轉換為'System.Collections.Generic.Dictionary<System.Enum,System.Collections.Generic.List<string>>
'“
即使Reporter.CriticalFailureCategory是枚舉。 我顯然是用錯誤的方式做的,但是我覺得應該有某種方法可以實現它。
這是目前Reporter.CriticalFailureCategory的定義:
namespace Reporter
{
[DataContract(Namespace = "")]
public enum CriticalFailureCategory
{
[EnumMember]
ExcessiveFailures,
[EnumMember]
StalledInConfiguration
}
}
這個想法是,可以無限擴展它,而不必重寫報告該代碼的代碼。
您需要使CountEnumOccurrence
通用才能起作用。
private static Dictionary<string, int> CountEnumOccurrence<TEnum>(
Dictionary<TEnum, List<string>> valueSource)
{
var convertedDictionary = new Dictionary<string, int>();
foreach (var entry in valueSource)
{
var name = Enum.GetName(entry.Key.GetType(), entry.Key);
convertedDictionary.Add(name, entry.Value.Count);
}
return convertedDictionary;
}
如果要將TEnum
類型限制為僅枚舉,則可以查看此問題,以了解如何以及為什么必須進行部分運行時檢查,或者必須編寫MSIL。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.