简体   繁体   English

如何创建泛型方法并创建该类型的实例

[英]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, eg: 当我调用该方法时,我想指定MyHtmlTag的类型,例如MyAnchor,例如:

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

or 要么

<%= 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() ? Activator.CreateInstance()吗?

Thanks 谢谢

Dave 戴夫

You'd use Activator.CreateInstance<T> : 您将使用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 ". MvcContrib中有现有功能,您可能要签出一个名为“ 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: 您需要将new()的通用约束添加到T,然后执行以下操作:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM