【问题标题】:Can not cast integer to Enum in Generic method [duplicate]无法在通用方法中将整数转换为枚举 [重复]
【发布时间】:2017-08-17 23:02:10
【问题描述】:

我发现c#不允许泛型类型为enum,所以我在网上查了一下,找到了这个线程Anyone know a good workaround for the lack of an enum generic constraint?,然后我安装了nuget包,但是在我的扩展方法中,(T)x.ToInteger() throws 不能转换类型'int' 到 'T'。因此GetDescription() 也不起作用,因为这是我获取枚举值描述的另一种枚举扩展方法。如果我用指定的枚举替换“T”,下面的代码将起作用。任何帮助表示赞赏。 这是我的扩展方法:

public static string ToEnumDescription<T>(this string enumValue) 
    where T: struct, IEnumConstraint
{
    if (enumValue.IsNullOrEmpty()) return string.Empty;
    var list = enumValue.Split(',');
    var descriptionList = new List<String>();
    foreach (var x in list)
    {
        var description = (x.IsInteger() && Enum.IsDefined(typeof(T), x.ToInteger())) 
            ? ((T)x.ToInteger()).GetDescription() 
            : string.Empty;
        descriptionList.Add(description);
    }
    return descriptionList.ToCommaSeperatedNoQuote();
}

【问题讨论】:

    标签: c# generics enums unconstrained-melody


    【解决方案1】:

    作为一种解决方法,您应该可以使用 (T)(object)x.ToInteger() 而不是 (T)x.ToInteger()

    这涉及对值进行装箱和拆箱,但这很可能不是重要的性能问题。

    【讨论】:

    • 好极了,现在我可以将 int 转换为 T,但是 'T' 必须转换为 System.Enum 才能使用 GetDescription() 扩展方法。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-03-23
    • 2013-08-25
    • 1970-01-01
    • 2011-05-09
    • 1970-01-01
    • 2011-07-10
    • 2013-02-04
    相关资源
    最近更新 更多