问题
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?
回答1:
That is a new C# 3.0 feature called extension method.
It means, that you add a new method to your ModelStateDictionary objects. You can call it like a normal method:
yourModelStateDictionary.AddRuleViolations( errors );
See, that the first parameter (the 'this'-parameter) is skipped. It assigns just ModelStateDictionary as a valid target for your extension method.
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).
回答2:
It means the method in question is an "extension method" and can be called as if it was a method of the class itself. See this article.
回答3:
It is an extention method signature, It means the "AddRuleViolations" will be treated as an extention method of ModelStateDictionary.
From MSDN.
Extension methods enable you to "add" methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type. Extension methods are a special kind of static method, but they are called as if they were instance methods on the extended type. For client code written in C# and Visual Basic, there is no apparent difference between calling an extension method and the methods that are actually defined in a type.
回答4:
Also see here: Extension Methods (C# Programming Guid)
回答5:
It adds an extension method to all instances of ModelStateDictionary.
来源:https://stackoverflow.com/questions/972433/what-does-this-mean-when-used-as-a-prefix-for-method-parameters