Delegate(委派)筆記

  • 2744
  • 0

Delegate(委派)筆記

Dotblogs 的標籤: ,

委派功能筆記:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DelegatePractice
{
  //Step 1: Declare delegate, defines required signature
  public delegate void MyDel(string name);

  internal class Program
  {
    //Step 2: Regular method that matches signature
    private static void SayHi(string name)
    {
      Console.WriteLine("HiHi~~ dear " + name);
    }

    private static void SayHello(string name)
    {
      Console.WriteLine("Hello, " + name);
    }

    private static void Main(string[] args)
    {
      //Step 3-1: Instantiate delegate with named method (MyDel)
      MyDel d1 = new MyDel(SayHi);
      MyDel d2 = new MyDel(SayHello);
      //Step 3-2: Invoke d1
      d1("Ken");
      //HiHi~~ dear Ken

      //Step 4-1: Append delegate d2 to delegate d1
      d1 += d2;
      //Step 4-2: Invoke d1, d2 also invoked
      d1("Leo");
      //HiHi~~ dear Leo
      //Hello, Leo

      //Step 5: Remove delegate d2 from delegate d1
      d1 -= d2;

      //Step 6-1: Instantiate delegate d3 with anonymous method
      MyDel d3 = delegate(string name)
      {
        Console.WriteLine("My name is " + name);
      };
      //Step 6-2: Invoke d3
      d3("Alex");
      //My name is Alex
    }
  }
}

參考資料:Delegate 類別

--------
沒什麼特別的~
不過是一些筆記而已