我读了很多类似的帖子和博客
ASP.NET MVC中基于代理的强类型URL生成
但他们中没有一个人真的做我想做的事.目前我有一个混合方法,如:
// shortened for Brevity public static Exts { public string Action(this UrlHelper url, Expression> expression) where T : ControllerBase { return Exts.Action(url, expression, null); } public string Action(this UrlHelper url, Expression > expression, object routeValues) where T : ControllerBase { string controller; string action; // extension method expression.GetControllerAndAction(out controller, out action); var result = url.Action(action, controller, routeValues); return result; } }
如果你的控制器方法没有任何参数,那么效果很好:
public class MyController : Controller { public ActionResult MyMethod() { return null; } public ActionResult MyMethod2(int id) { return null; } }
然后我可以:
Url.Action(c => c.MyMethod())
但是如果我的方法接受一个参数,那么我必须传递一个值(我永远不会使用):
Url.Action(c => c.MyMethod2(-1), new { id = 99 })
所以问题是有一种方法可以改变扩展方法,仍然要求第一个参数是一个在类型T
上定义的方法,它确保返回参数是一个ActionResult
没有实际指定参数的类型,如:
Url.Action(c => c.MyMethod2, new { id = 99 })
所以这会传递一个指向方法的指针(比如反射MethodInfo
)而不是Func<>
它,所以它不会关心参数.如果有可能,那签名会是什么样子?