简体   繁体   中英

How to implement C# Extension methods accepting anonymous type

In ASP.NET MVC there are plenty of Helpers accepting anonymous types as argument and generating input.

For example:

@Html.Action("Action", "Controler", new {routeVal1 = 1, routeVal2 = 2})

My question is how to implement my own extensions accepting anonymous type. Should i reference it as object and use reflection or there is more elegant solution?

You can use dynamic instead of object .

Visual C# 2010 introduces a new type, dynamic. The type is a static type, but an object of type dynamic bypasses static type checking. In most cases, it functions like it has type object. At compile time, an element that is typed as dynamic is assumed to support any operation. Therefore, you do not have to be concerned about whether the object gets its value from a COM API, from a dynamic language such as IronPython, from the HTML Document Object Model (DOM), from reflection, or from somewhere else in the program. However, if the code is not valid, errors are caught at run time.

right firstly i am assuming you are righting extensions for the @HTML object what you need to do is create the method with

RouteValueDictionary class

so it becomes public static mvchtmlstring Foo(string Action, string Controller, RouteValueDictionary values)

then you have in the function call

        TagBuilder tb = new TagBuilder("D");
        tb.Attributes.Add();

so the whole thing becomes

public static mvchtmlstring Foo(string taglabel, string url, RouteValueDictionary values)
{


            TagBuilder tb = new TagBuilder("a");
tb.Attrubutes.add("href",url);
tb.setInnerText(taglabel);
            tb.MergeAttributes(values);
return new MvcHtmlString(tb.toString());
}

then the call is

@Html.Foo("Bar","Http://www.stackoverflow.com",new {Id="d", class="dd"})

BTW RouteValueDictionary Inherits from IDictionary so your class can have a signature for that too.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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