Skip to main content
 首页 » 编程设计

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

2024年02月20日8jackei

在 ASP.NET MVC 中有大量的 Helpers 接受匿名类型作为参数并生成输入。

例如:

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

我的问题是如何实现我自己的接受匿名类型的扩展。我应该将它作为对象引用并使用反射还是有更优雅的解决方案?

请您参考如下方法:

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