簡體   English   中英

在一個類中聲明靜態方法並將其用作另一個類的方法

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

我正在為ASP.NET MVC做Nerd Dinner教程 ,我在C#語言中遇到了一個看起來非常奇怪的構造。 這個問題的標題有點模糊,因為我無法定義這是什么。 這也使我很難搜索這個主題,因此我決定提出一個問題。

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

后來他們表明:

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

困擾我的部分是:

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

ModelState.AddRuleViolations(dinner.GetRuleViolations());

看起來您在ControllerHelpers類中定義AddRuleViolations函數,然后調用它,就像它是ModelState屬性的實例函數一樣。 這個觀察是否正確? 如果是,你為什么需要這個? 我覺得在一個類中定義一個方法就好像它是另一個類的方法一樣。

注意: ModelState是當前類的屬性,而不是它自己的類。

這是因為它是一種擴展方法 這就是第一個參數開頭的“this”位。

擴展方法的想法是它們允許您有效地向現有類添加功能。 所以如果你有:

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

然后你可以這樣稱呼它:

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

這實際上是編譯好像你寫的:

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

必須在頂級非泛型靜態類中聲明擴展方法。 它們在LINQ中被大量使用。

這種觀察確實是正確的; 這是一個擴展方法 ,如參數類型之前的this修飾符所示:

this ModelStateDictionary modelState

然后編譯器將解析對方法的調用, 看起來ModelStateDictionary的實例方法,但請注意它實際上仍然靜態調用 - 所以:

obj.SomeStaticMethod(arg1, arg2);

實際編譯為:

TheDeclaringType.SomeStaticMethod(obj, arg1, arg2);

這可能導致諸如obj奇怪現象可能為null ,並且調用仍然有效

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM