简体   繁体   English

如何实现接受匿名类型的C#扩展方法

[英]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. 在ASP.NET MVC中,有很多Helpers接受匿名类型作为参数并生成输入。

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 . 您可以使用dynamic而不是object

Visual C# 2010 introduces a new type, dynamic. Visual C#2010引入了一种新的动态类型。 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. 因此,您不必担心对象是从COM API,动态语言(如IronPython),HTML文档对象模型(DOM),反射还是程序中的其他位置获取其值。 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 首先,我假设你正在为@HTML对象扩展,你需要做的是创建方法

RouteValueDictionary class RouteValueDictionary类

so it becomes public static mvchtmlstring Foo(string Action, string Controller, RouteValueDictionary values) 所以它成为公共静态mvchtmlstring Foo(字符串Action,字符串Controller,RouteValueDictionary值)

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. BTW RouteValueDictionary继承自IDictionary,因此您的类也可以拥有该签名。

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

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