Using Generics to Create HtmlHelper Extension Methods

前端 未结 2 664
北海茫月
北海茫月 2021-01-23 11:02

I\'m not really familiar with creating generic methods, so I thought I\'d put this question to the community & see what comes back. It might not even be a valid use of gener

2条回答
  •  广开言路
    2021-01-23 11:18

    For what you're trying to do, I think the main benefit of using generics would be to take advantage of type inference. If you declare your method as follows :

    public static string GetTag(this HtmlHelper h, T myObj, TagBuilder tag)
    

    You won't have to specify the type parameter when calling it, because it will be inferred from the usage (i.e. the compiler will see that the second parameter's type is MyType, so it will guess that T == MyType).

    But anyway, you don't really need to specify the type : the method could call GetType on the object, and use the resulting type the same way it would have used typeof(T), so generics aren't so useful here.

    However, I see one reason to use them anyway : if you have an object of type MySubType, which inherits from MyType, you might want to render only properties defined in MyType : in that case you just have to specify MyType as the type parameter, overriding the type inference.

    Here's a possible implementation :

    public static string GetTag(this HtmlHelper h, T myObj, TagBuilder tag)
    {
        Type t = typeof(T);
        tag.Attributes.Add("class", t.Name);
        foreach (PropertyInfo prop in t.GetProperties())
        {
            object propValue = prop.GetValue(myObj, null);
            string stringValue = propValue != null ? propValue.ToString() : String.Empty;
            tag.Attributes.Add(prop.Name, stringValue);
        }
        return tag.ToString();
    }
    

提交回复
热议问题