我知道泛型是在编译时完成的,但我对泛型的工作方式感到困惑(虽然我知道泛型......)。
我创建了以下扩展方法:
public static class EnumExt
{
/// <summary>
/// Gets the description, if any, or the name of the enum as a string in a enum type
/// </summary>
public static string GetDescription<T>(this T enumType) where T : struct, IConvertible
{
FieldInfo fieldInfo = enumType.GetType().GetField(enumType.ToString());
DescriptionAttribute[] descriptionAttributes = (DescriptionAttribute[])
fieldInfo.GetCustomAttributes(typeof(DescriptionAttribute), false);
if (descriptionAttributes.Length > 0)
{
return descriptionAttributes[0].Description;
}
return enumType.ToString();
}
}
我以下面的枚举为例
namespace MyProject.Model
{
[Flags]
public enum MyEnumType
{
[Description("None")]
None = 0,
[Description("Show Products (default)")]
Products = 1,
[Description("Show Tariffs")]
Tariffs = 2
}
}
现在我想在 MVC 中的 HttpHelper 中使用它,它返回一个像这样的字符串(html 文本)。请注意我的类(class)可以访问我的 EnumExt 方法。
public static IHtmlString CheckBoxesForEnumModel<TModel>(this HtmlHelper<TModel> htmlHelper)
{
if (!typeof(TModel).IsEnum)
{
throw new ArgumentException("this helper can only be used with enums");
}
TModel[] allEnumValues = (TModel[])Enum.GetValues(typeof(TModel));
foreach (TModel item in allEnumValues)
{
var descErr = item.GetDescription(); //does not compile, but I know it's a MyEnumType.Tariffs..
var descOk = MyEnumType.Tariffs.GetDescription(); //this line works
//descOk = "Show Tariffs"
}
return new HtmlString("ideally this is some html checkboxes with each enum description");
}
我知道我可以获取所有枚举值并使用 TModel 像这样遍历它们:
TModel[] allEnumValues = (TModel[])Enum.GetValues(typeof(TModel));
但如果我知道 TModel 是一个枚举(它是一个 MyEnumType),为什么我不能使用它来访问枚举扩展方法,例如:
allValues[0].GetDescription<>(); //ERROR. this does not compile
我想这是因为我必须以某种方式将它转换为特定类型,如 MyEnumType,但如何做到这一点并使其保持通用?
提前致谢!
更新:多亏了第一个答案,我才能够通过将 TModel
限制为 struct, IConvertible
最佳答案
因为您的扩展方法是为 T 定义的,其中 T : struct, IConvertible
。
但是 CheckBoxesForEnumModel
中的 TModel
不符合这些通用类型约束。
你应该改变签名
public static IHtmlString CheckBoxesForEnumModel<TModel>(this HtmlHelper<TModel> htmlHelper)
到
public static IHtmlString CheckBoxesForEnumModel<TModel>(this HtmlHelper<TModel> htmlHelper)
where TModel : struct, IConvertible
或更严格。
关于c# - 无法将枚举扩展方法与泛型一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31822735/