Is it possible to create a generic method with a definition similar to:
public static string GenerateWidget<TypeOfHtmlGen, WidgetType>(this HtmlHelper htmlHelper
, object modelData)
// TypeOfHtmlGenerator is a type that creates custom Html tags.
// GenerateWidget creates custom Html tags which contains Html representing the Widget.
I can use this method to create any kind of widget contained within any kind of Ht开发者_JAVA技巧ml tag.
Thanks
Yes you can write this generic extension method. But since it does not use any of its type-parameters in the function signature, you will always have to specify the types. That means you cannot use:
string r = helper.GenerateWidget(modelData);
but you will always need:
string r = helper.GenerateWidget<SpecificHtmlGenerator, SpecificWidget>(modelData);
There's a few improvements you might want to add, because it looks like you're going to have to instanciate those classes within your method:
public static string GenerateWidget<TypeOfHtmlGen, WidgetType>(this HtmlHelper htmlHelper
, object modelData)
where TypeOfHtmlGen: new()
where WidgetType: new()
{
// Awesome stuff
}
Also, you're probably going to want the widget and html gen to implment some sort of interface or base class:
public static string GenerateWidget<TypeOfHtmlGen, WidgetType>(this HtmlHelper htmlHelper
, object modelData)
where TypeOfHtmlGen: HtmlGenBaseClass, new()
where WidgetType: WidgetBaseClass, new()
{
// Awesome stuff
}
精彩评论