【问题标题】:How to create a generic enum method?如何创建通用枚举方法?
【发布时间】:2018-04-18 16:38:59
【问题描述】:

我的代码中有以下两种方法,它们基本上将枚举转换为整数和字符串的字典:

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

由于这两个方法的代码基本相同,所以我想写一个通用方法,看起来像这样:

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;

    }

问题在于,由于 C# 没有通用枚举包含该方法无法将 T 识别为枚举,因此我无法转换为 int。

如何在不完全编写新函数的情况下解决这个问题?

【问题讨论】:

  • 当你最终 casting 时,为什么你想要一个泛型方法?在任何情况下,所有枚举都是System.Enum 类型的实例
  • Enum to Dictionary c#的可能重复
  • @JamesThorpe 感谢您的链接。我想我可以通过这种方式实现功能来解决问题
  • @ShaiAharoni 阅读一些答案 - 其中之一就是您想要的确切通用函数。
  • 基本上,您只需将(int)value 替换为Convert.ToInt32(value) 即可修复您的尝试

标签: c#


【解决方案1】:

就像@thmshd 建议的那样,我用 Convert.ToInt32 替换了显式 int 强制转换,它似乎解决了这个问题。所以该方法的最终版本是:

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

【讨论】:

    猜你喜欢
    • 2021-12-13
    • 2015-10-19
    • 1970-01-01
    • 1970-01-01
    • 2010-09-09
    相关资源
    最近更新 更多