开发者

How to Create a Generic Method and Create Instance of The Type

I want to create a helper method that I can imagine has a signature similar to this:

public static MyHtmlTag GenerateTag<T>(this HtmlHelper htmlHelper, object obj)
{
    // how do I create an instance of MyAnchor? 
    // this returns MyAnchor, which has a MyHtmlTag base
}

When I invoke the method, I want to specify a type of MyHtmlTag, such as MyAnchor, e.g.:

<%= Html.GenerateTag<MyAnchor>(obj) %>

or

&l开发者_如何学运维t;%= Html.GenerateTag<MySpan>(obj) %>

Can someone show me how to create this method?

Also, what's involved in creating an instance of the type I specified? Activator.CreateInstance()?

Thanks

Dave


You'd use Activator.CreateInstance<T>:

public static MyHtmlTag GenerateTag<T>(this HtmlHelper htmlHelper, object obj)
{
    T value = Activator.CreateInstance<T>();
    // Set properties on value/ use it/etc
    return value;
}


There's existing functionality in MvcContrib you may want to check out called "FluentHtml". It looks like this:

<%=this.TextBox(x => x.FirstName).Class("required").Label("First Name:")%>
<%=this.Select(x => x.ClientId).Options((SelectList)ViewData["clients"]).Label("Client:")%>
<%=this.MultiSelect(x => x.UserId).Options(ViewModel.Users)%>
<%=this.CheckBox("enabled").LabelAfter("Enabled").Title("Click to enable.").Styles(vertical_align => "middle")%>


You need to add the generic constraint of new() to T, then do the following:

public static MyHtmlTag GenerateTag<T> (this HtmlHelper helper, T obj) where T : MyHtmlTag, new()
{
    T val = new T ();
    return val;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜