简体   繁体   English

在一个类中声明静态方法并将其用作另一个类的方法

[英]Declaring a static method in one class and using it as a method of another class

I am doing the Nerd Dinner tutorial for ASP.NET MVC and I met one construction in the C# language that seemed very strange. 我正在为ASP.NET MVC做Nerd Dinner教程 ,我在C#语言中遇到了一个看起来非常奇怪的构造。 The title of this question is a bit vague, because I have trouble defining what this is. 这个问题的标题有点模糊,因为我无法定义这是什么。 This also made it difficult for me to search about the topic, hence I decide to ask a question about it. 这也使我很难搜索这个主题,因此我决定提出一个问题。

In the Nerd Dinner tutorial I see the following code fragment: Nerd Dinner教程中,我看到以下代码片段:

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

And later they show: 后来他们表明:

//
// GET: /Dinners/Edit/2

public ActionResult Edit(int id) {

    Dinner dinner = dinnerRepository.GetDinner(id);

    return View(dinner);
}

//
// POST: /Dinners/Edit/2

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Edit(int id, FormCollection formValues) {

    Dinner dinner = dinnerRepository.GetDinner(id);

    try {

        UpdateModel(dinner);

        dinnerRepository.Save();

        return RedirectToAction("Details", new { id=dinner.DinnerID });
    }
    catch {

        ModelState.AddRuleViolations(dinner.GetRuleViolations());

        return View(dinner);
    }
}

The parts that puzzle me are: 困扰我的部分是:

public static void AddRuleViolations(this ModelStateDictionary modelState, IEnumerable<RuleViolation> errors) 

and

ModelState.AddRuleViolations(dinner.GetRuleViolations());

It looks like you define the AddRuleViolations function in the ControllerHelpers class and then invoke it as if it was an instance function of the ModelState property. 看起来您在ControllerHelpers类中定义AddRuleViolations函数,然后调用它,就像它是ModelState属性的实例函数一样。 Is this observation correct? 这个观察是否正确? If yes, why would you need this? 如果是,你为什么需要这个? It looks very strange to me to define a method in one class as if it was a method of another class. 我觉得在一个类中定义一个方法就好像它是另一个类的方法一样。

Note: ModelState is a property of the current class and not a class it self. 注意: ModelState是当前类的属性,而不是它自己的类。

It's because it's an extension method . 这是因为它是一种扩展方法 That's what the "this" bit is at the start of the first parameter. 这就是第一个参数开头的“this”位。

The idea of extension methods is that they allow you to effectively add functionality to existing classes. 扩展方法的想法是它们允许您有效地向现有类添加功能。 So if you have: 所以如果你有:

public static class StringExtensions
{
    public static string Reverse(this string text)
    {
        char[] chars = text.ToCharArray();
        Array.Reverse(chars);
        return new string(chars);
    }
}

then you can call it like this: 然后你可以这样称呼它:

string x = "hello world";
string y = x.Reverse();

that actually gets compiled as if you'd written: 这实际上是编译好像你写的:

string x = "hello world";
string y = StringExtensions.Reverse(x);

Extension methods have to be declared in top-level non-generic static classes. 必须在顶级非泛型静态类中声明扩展方法。 They're heavily used in LINQ. 它们在LINQ中被大量使用。

That observation is indeed correct; 这种观察确实是正确的; this is an extension method , as noted by the this modifier before the parameter-type: 这是一个扩展方法 ,如参数类型之前的this修饰符所示:

this ModelStateDictionary modelState

The compiler will then resolve calls to the method looking like an instance method of ModelStateDictionary , but note that it is still actually a static call - so: 然后编译器将解析对方法的调用, 看起来ModelStateDictionary的实例方法,但请注意它实际上仍然静态调用 - 所以:

obj.SomeStaticMethod(arg1, arg2);

is actually compiled as: 实际编译为:

TheDeclaringType.SomeStaticMethod(obj, arg1, arg2);

which can result in oddities such as obj can be null and the call will still work . 这可能导致诸如obj奇怪现象可能为null ,并且调用仍然有效

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM