如何创建通用枚举方法?

时间:2017-11-06 13:36:41

标签: c#

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

  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。

如果不完全编写新功能,如何解决这个问题呢?

1 个答案:

答案 0 :(得分:0)

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

Dim objRow As DataRow
Dim customFlds As Dictionary(Of String, String) = m_objCmnFncs.getCustomFlsdWithUnlimitedDataIndicator(strOrgId)
Dim fldListWithUnlimitedDataEnabled As List(Of String) = (From kv As KeyValuePair(Of String, String) In customFlds
                                                          Where kv.Value.Equals("Y")
                                                          Select kv.Key).ToList
If fldListWithUnlimitedDataEnabled.Count > 0 Then

    For Each objRow In objDt.Rows
        //The below condition effects the performance
        If fldListWithUnlimitedDataEnabled.Contains(objRow("custom_id")) Then
            objRow.Delete()
        End If
    Next
End If