InG*_*eek 18 c# extension-methods html-helper
namespace System.Web.Mvc.Html
{
// Summary:
// Represents support for HTML in an application.
public static class FormExtensions
{
public static MvcForm BeginForm(this HtmlHelper htmlHelper, string actionName, string controllerName);
...
}
}
Run Code Online (Sandbox Code Playgroud)
我注意到,BeginForm方法中第一个参数前面的'this'对象似乎不被接受为参数.看起来在真正的BeginForm方法中的功能如下:
BeginForm(string actionName, string controllerName);
Run Code Online (Sandbox Code Playgroud)
省略第一个参数.但它实际上以隐藏的方式以某种方式接收第一个参数.能告诉我这个结构是如何工作的吗?我实际上正在探索MVC 4互联网示例.谢谢.
Yai*_*vet 30
这就是扩展方法在C#中的工作方式.扩展方法功能允许您使用自定义方法扩展现有类型.this [TypeName]方法参数上下文中的关键字是type您希望使用自定义方法扩展的关键字this,在您的情况下用作前缀,HtmlHelper是type扩展,并且BeginForm是应该扩展它的方法.
看看这个string类型的简单扩展方法:
public static bool BiggerThan(this string theString, int minChars)
{
return (theString.Length > minChars);
}
Run Code Online (Sandbox Code Playgroud)
您可以轻松地在string对象上使用它:
var isBigger = "my string is bigger than 20 chars?".BiggerThan(20);
Run Code Online (Sandbox Code Playgroud)
参考文献:
详细记录的参考文献将是:如何:实现和调用自定义扩展方法(C#编程指南)
关于ASP.NET MVC中的扩展方法的更具体的参考将是: 如何创建自定义MVC扩展方法