什么是'这个'关键字的方法的参数是什么意思? [英] What does 'this' keyword mean in a method parameter?

查看:247
本文介绍了什么是'这个'关键字的方法的参数是什么意思?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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);
...
    }
}



我注意到,在BeginForm方法的第一个参数前'这个'对象似乎不被接受作为参数。在现实BeginForm方法的函数看起来如下:

I have noticed that 'this' object in front of the first parameter in BeginForm method doesn't seem to be accepted as a parameter. Looks like in real BeginForm methods functions as:

BeginForm(string actionName, string controllerName);



省略第一个参数。但它实际上接收到的第一个参数莫名其妙地在一个隐藏的方式。
能否请您给我解释一下这个结构是如何工作的。其实我探索MVC 4互联网样品。
谢谢你。

omitting the first parameter. But it actually receives that first parameter somehow in a hidden way. Can you please explain me how this structure works. I actually exploring MVC 4 internet Sample. Thank you.

推荐答案

这是扩展方法如何在C#。扩展方法的功能,让您用自定义方法扩展现有类型。
中的在方法的参数方面,这[类型名] 关键字是键入要延长与自定义的方法,在这个作为前缀,你的情况,的HtmlHelper 键入来扩展和 BeginForm 是要扩展它的方法。

This is how extension methods works in C#. The Extension Methods feature allowing you to extend existing types with custom methods. The this [TypeName] keyword in the context of method's parameters is the type that you want to extend with your custom methods, the this is used as a prefix, in your case, HtmlHelper is the type to extend and BeginForm is the method which should extend it.

看看为字符串这种简单的延伸方式类型:

public static bool BiggerThan(this string theString, int minChars)
{
  return (theString.Length > minChars);
}

您可以轻松地使用它字符串目标:

You can easily use it on string object:

var isBigger = "my string is bigger than 20 chars?".BiggerThan(20);



参考文献:

References:

有关在ASP.NET MVC延伸方法更具体的参考是:
如何创建自定义MVC扩展方法

More particular reference about Extention Methods in ASP.NET MVC would be: How To Create Custom MVC Extension Methods

这篇关于什么是'这个'关键字的方法的参数是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆