ASP.NET - Delegate 委派

  • 13337
  • 0

此篇簡單介紹ASP.NET中的委派。


 

示範基本委派 : 

using System;

class A
{
    // 宣告委派簽章,同時也宣告指向何種"方法結構"。回傳與參數
    public delegate void MyDelegate(string aValue);
    public event MyDelegate MyEvent; // 宣告對應委派之事件
    private string MyProperty = "classA_";

    private void classA_Method()
    {
        B obB1 = new B();
        this.MyEvent += new MyDelegate(obB1.classB_Method); // 註冊方法
        this.MyEvent(this.MyProperty); // 觸發委派事件
    }
}

class B
{
    private string MyProperty = "classB_";

    public void classB_Method(string bValue)
    {
        if (!String.IsNullOrEmpty(bValue))
            this.MyProperty += bValue;
        else
            throw new NotImplementedException();
    }
}

示範參數傳遞自選方法 : 

class C
{
    public delegate string MyDelegate2(string aValue); // 宣告委派簽章

    public void chanceSelfMehotd()
    {
        string anserRequest = this.doOtherMethod("MySet", this.classA_MyUseMehotd);
        // 自己選擇要用什麼方法,後由一個管理的主方法來執行相對應的事情
    }

    // 注意這裡的第二個參數,是委派型態
    private string doOtherMethod(string pString, MyDelegate2 youChanceMethod)
    {
        string methodString = youChanceMethod(pString); // 別人自選方法
        return methodString + "afterSet"; // 別人的方法做完事情後,自己加工後回傳
    }
    
    // 自定義的方法
    private string classA_MyUseMehotd(string myValue)
    {
        string mySet = myValue + "_MySet";
        if (!String.IsNullOrEmpty(myValue))
            return mySet;
        else
            throw new NotImplementedException();
    }
}

 

委派參考網站

 


多多指教!! 歡迎交流!!

你不知道自己不知道,那你會以為你知道