简体   繁体   English

如何创建通用枚举方法?

[英]How to create a generic enum method?

I have the following 2 methods in my code that basically turn an enum into a dictionay of ints and strings: 我的代码中有以下两种方法,这些方法基本上将枚举转换为整数和字符串的字典:

  public Dictionary<int, string> GetChannelLevels()
    {
        IEnumerable<ChannelLevel> enumValues = Enum.GetValues(typeof(ChannelLevel)).Cast<ChannelLevel>();

        var channelLevels = enumValues.ToDictionary(value => (int)value, value => value.ToString());

        return channelLevels;
    }


    public Dictionary<int, string> GetCategoryLevels()
    {
        IEnumerable<CategoryLevel> enumValues = Enum.GetValues(typeof(CategoryLevel)).Cast<CategoryLevel>();

        var channelLevels = enumValues.ToDictionary(value => (int)value, value => value.ToString());

        return channelLevels;
    }

Since the code of these 2 methods is basically the same, I thought of writing a generic method which would look something like this: 由于这两种方法的代码基本相同,因此我想编写一个通用方法,如下所示:

private Dictionary<int, string> GetEnumDictionary<T>() where T : struct, IConvertible 
    {
        if (!typeof(T).IsEnum)
        {
            throw new ArgumentException("T must be an enumerated type");
        }



        IEnumerable<T> enumValues = Enum.GetValues(typeof(T)).Cast<T>();

        var channelLevels = enumValues.ToDictionary(value => /*THIS IS WHERE THE PROBLEM IS*/  (int)value, value => value.ToString());

        return channelLevels;

    }

The problem is that since C# doesn't have a generic enum constaints the method cann't recognize T as an enum and therefore I cann't convery in to int. 问题在于,由于C#没有通用枚举,该方法无法将T识别为枚举,因此我不能精于int。

How can I solve this problem without writing a new function altogether? 如何在不完全编写新函数的情况下解决此问题?

Like @thmshd suggested i replaced the explicit int casting with Convert.ToInt32 and it seems to solve the problem. 就像@thmshd建议的那样,我用Convert.ToInt32替换了显式int强制转换,这似乎可以解决问题。 So the final version of the method is: 因此,该方法的最终版本是:

private Dictionary<int, string> GetEnumDictionary<T>() where T : struct, IConvertible 
{
    if (!typeof(T).IsEnum)
    {
        throw new ArgumentException("T must be an enumerated type");
    }

    IEnumerable<T> enumValues = Enum.GetValues(typeof(T)).Cast<T>();

    var enumDictionary = enumValues.ToDictionary(value => Convert.ToInt32(value), value => value.ToString());

    return enumDictionary;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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