&是什么QUOT;本"作为方法参数的前缀使用时,是什么意思? [英] What does "this" mean when used as a prefix for method parameters?
问题描述
我敢肯定,答案是显而易见的东西,而我有点不好意思,我真的不知道答案了,但考虑下面的代码示例我拿起在阅读专业ASP.NET MVC 1.0
I'm sure the answer is something obvious, and I'm kind of embarrassed that I don't really know the answer already, but consider the following code sample I picked up while reading "Professional ASP.NET MVC 1.0":
public static class ControllerHelpers
{
public static void AddRuleViolations(this ModelStateDictionary modelState, IEnumerable<RuleViolation> errors)
{
foreach (RuleViolation issue in errors)
modelState.AddModelError(issue.PropertyName, issue.ErrorMessage);
}
}
我明白这是什么静态方法是干什么的,但什么我不明白的是本是在方法签名服务的目的是什么字。任何人都可以告诉我吗?
I understand what this static method is doing, but what I don't understand is what purpose the word "this" is serving in the method signature. Can anyone enlighten me?
推荐答案
这是一个新的名为C#3.0功能的扩展方法。
That is a new C# 3.0 feature called extension method.
这意味着,您添加一个新的方法你ModelStateDictionary对象。你可以把它像一个正常的方法:
It means, that you add a new method to your ModelStateDictionary objects. You can call it like a normal method:
yourModelStateDictionary.AddRuleViolations( errors );
请参阅,第一个参数(即this'参数)被跳过。它赋予只是ModelStateDictionary为您的扩展方法的有效目标
See, that the first parameter (the 'this'-parameter) is skipped. It assigns just ModelStateDictionary as a valid target for your extension method.
线索是,你可以用任何类做到这一点 - 即使封存或第三方类,等等。 .Net框架类(例如在对象或字符串)。
The clue is, that you can do this with any class - even sealed or 3rd party classes, like .Net framework classes (for instance on object or string).
这篇关于&是什么QUOT;本"作为方法参数的前缀使用时,是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!