【发布时间】: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