我知道泛型是在编译时完成的,但是我对泛型的工作方式感到困惑(我曾经认为我了解泛型..)。
我创建了以下扩展方法:
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文本),如下所示。请注意,我的类可以访问我的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来编译。
TModel
也应该是struct, IConvertble
。 - tukaefTModel
限制为struct, IConvertible
并且无法使之成为枚举,因此我不能再使用GetDescription枚举扩展方法,因为它不再是“真正的”枚举? 我可以编译但item.GetDescription()
没有返回“Show Tariffs”,而是“Tariffs”。 - diegosasw