partial 方法 (C# 參考)partial method (C# Reference)

部分方法會在部分型別的某一部分中定義其簽章,並在類型的另一部分中定義其實作。A partial method has its signature defined in one part of a partial type, and its implementation defined in another part of the type. 部分方法可讓類別設計工具提供方法攔截程序,類似於事件處理常式,開發人員可以決定是否實作。Partial methods enable class designers to provide method hooks, similar to event handlers, that developers may decide to implement or not. 如果開發人員未提供實作,編譯器會在編譯時期移除簽章。If the developer does not supply an implementation, the compiler removes the signature at compile time. 下列條件適用於部分方法:The following conditions apply to partial methods:

  • 部分型別的兩個部分中的簽章必須相符。Signatures in both parts of the partial type must match.

  • 此方法必須傳回 void。The method must return void.

  • 不允許存取修飾詞。No access modifiers are allowed. 部分方法都是隱含私用。Partial methods are implicitly private.

下列範例顯示部分類別之兩個部分中定義的部分方法:The following example shows a partial method defined in two parts of a partial class:

namespace PM
{
    partial class A
    {
        partial void OnSomethingHappened(string s);
    }

    // This part can be in a separate file.
    partial class A
    {
        // Comment out this method and the program
        // will still compile.
        partial void OnSomethingHappened(String s)
        {
            Console.WriteLine("Something happened: {0}", s);
        }
    }
}

如需詳細資訊,請參閱部分類別和方法For more information, see Partial Classes and Methods.

另請參閱See also