简体   繁体   中英

How to pass a generic Enum as dictionary key in method parameter

I'm trying to create a method that counts the number of times a given Enum occurs within some existing dictionaries for reporting purposes:

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;
}

However, if I attempt to call this method like so:

var criticalFailureCounts = CountEnumOccurrence(reportSpan.criticalFailures));

I get

"cannot convert from ' System.Collections.Generic.Dictionary<Reporter.CriticalFailureCategory,System.Collections.Generic.List<string>> ' to ' System.Collections.Generic.Dictionary<System.Enum,System.Collections.Generic.List<string>> '"

Even though Reporter.CriticalFailureCategory is an Enum. I'm obviously doing this the wrong way, but I feel like there should be some way to achieve it.

Here's the definition for Reporter.CriticalFailureCategory at present:

namespace Reporter
{
    [DataContract(Namespace = "")]
    public enum CriticalFailureCategory
    {
        [EnumMember]
        ExcessiveFailures,
        [EnumMember]
        StalledInConfiguration
    }
}

The idea is that this can be expanded indefinitely without having to rewrite the code that reports on it.

You need to make CountEnumOccurrence generic for this to work.

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;
}

If you want to constrain the TEnum type to only enums you can check out this question to see how and why it has to be a partially run time check or you have to write MSIL.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM