C# - delegate(委派)

delegate類似於C語言的Function Pointer,允許定義參考物件來動態指向實體Method,並以呼叫此參考來執行特定實體Method,後來也延伸出匿名委派的功能,實體Method不需事先定義,而動態指定delegate運作邏輯。 

定義delegate參考物件,需與預定指向之實體Method有相同的Input/Output參數型別:

public delegate void ShowMessage(string);

定義n個相同Input/Output參數的實體Method,提供delegate指派:

public void Alert(string message){
    this.ClientScript.RegisterClientScriptBlock(
        this.GetType(),"alert","alert('"+message+"');",true);
}
public void Confirm(string message){
    this.ClientScript.RegisterClientScriptBlock(
        this.GetType(),"confirm","confirm('"+message+"');",true);
}
public void CustomMessage(string message){
    this.ClientScript.RegisterClientScriptBlock(
        this.GetType(),"customMessage","customMessage('"+message+"');",true);
}

指向實體Method&執行:

ShowMessage FunctionRef=new ShowMessage(Confirm);
FunctionRef("Alert Message");
FunctionRef=new ShowMessage(Alert);
FunctionRef("Confirm Message");
FunctionRef=new ShowMessage(CustomMessage);
FuncttionRef("CustomMessage Message");

匿名委派,不再事先定義實體Method,於Delegate宣告同時,指定參考Method的邏輯:

ShowMessage FunctionRef=delegate(string message){
    this.ClientScript.RegisterClientScriptBlock(
        this.GetType(),"alert","alert('"+message+"');",true);
};
FunctionRef("Alert Message");
ShowMessage FunctionRef=delegate(string message){
    this.ClientScript.RegisterClientScriptBlock(
        this.GetType(),"confirm","confirm('"+message+"');",true);
};
FunctionRef("Confirm Message");
ShowMessage FunctionRef=delegate(string message){
    this.ClientScript.RegisterClientScriptBlock(
        this.GetType(),"customMessage","customMessage('"+message+"');",true);
};
FunctionRef("CustomMessage Message");

沒有留言:

橫式廣告