C# 部分方法定義
部分類也可以定義部分方法(partial method)。部分方法在一個(gè)部分類中定義(沒有方法體),在另一個(gè)部分類中實(shí)現(xiàn)。在這兩個(gè)部分類中,都要使用partial關(guān)鍵字。
public partial class MyClass
{
partial void HyPartialMethod();
}
public partial class MyClass
{
pairbial void MyPartialMethod ()
{
// Method in^lementation
}
}
部分方法也可以是靜態(tài)的,但它們總是私有的,且不能有返回值。它們使用的任何參數(shù)都不能是out參數(shù),但可以是ref參數(shù)。部分方法也不能使用virtual、abstract、override、new、sealed或extern修飾符。
有了這些限制,就不太容易看出部分方法的作用了。實(shí)際上,部分方法的重要性體現(xiàn)在編譯代碼時(shí),而不是使用代碼時(shí)??紤]下面的代碼:
public partial class MyClass
{
partial void DoSomething&lse();
public void DoSomething()
{
WriteLine("DoSomething() execution started.");
DoSomethingBlse();
WriteLine("DoSomething(} execution finished.");
}
}
public partial class MyClass
{
partial void DoSomethingElse()=>
WriteLine("DoSomethingElse() called.");
}
在第一個(gè)部分類定義中定義和調(diào)用部分方法DoSomethingElse(),在第二個(gè)部分類中實(shí)現(xiàn)它。在控制臺(tái)應(yīng)用程序中調(diào)用DoSomething()方法時(shí),輸出如下內(nèi)容:
DoSomething() execution started.
DoSomethingElse() called.
DoSomething() execution finished.
如果刪除第二個(gè)部分類定義,或者刪除部分方法的全部實(shí)現(xiàn)代碼(或者注釋掉這部分代碼),輸出就如下所示:
DoSomething() execution started.
DoSomething() execution finished.
讀者可能認(rèn)為,調(diào)用DoSomethingElse()時(shí),運(yùn)行庫發(fā)現(xiàn)該方法沒有實(shí)現(xiàn)代碼,因此會(huì)繼續(xù)執(zhí)行下一行代碼。 但實(shí)際上,編譯代碼時(shí),如果代碼包含一個(gè)沒有實(shí)現(xiàn)代碼的部分方法,編譯器會(huì)完全刪除該方法,還會(huì)刪除對(duì)該方法的所有調(diào)用。執(zhí)行代碼時(shí),不會(huì)檢查實(shí)現(xiàn)代碼,因?yàn)闆]有要檢査的方法調(diào)用。這會(huì)略微提高性能。
與部分類一樣,在定制自動(dòng)生成的代碼或設(shè)計(jì)器創(chuàng)建的代碼時(shí),部分方法是很有用的。設(shè)計(jì)器會(huì)聲明部分方法,用戶根據(jù)具體情形選擇是否實(shí)現(xiàn)它。如果不實(shí)現(xiàn)它,就不會(huì)影響性能,因?yàn)樵诰幾g過的代碼中并不存在該方法。
點(diǎn)擊加載更多評(píng)論>>