提供一個範例
[背景說明]
1.
有一個 Class BBB,是一個加密程式,
有一個加密程序 EncodeProcessOfBBB()
其中,提供使用者由外部提供 加密API ,也就是 EncoderAPIfromOutSide
2.
有一個Class AAA,自備加密程式 EncoderMethodofAAA
想要使用 Class BBB 進行加密
-----------------------------------------
[執行流程說明]
1. 在AAA 裡面,實體化 Class BBB,
=> BBB insBBB = new BBB();
2. 接著 設定 BBB 使用 自備加密程式
=> insBBB.EncoderAPIfromOutSide = EncoderMethodofAAA;
3. 執行 加密程序
=> insBBB.EncodeProcessOfBBB();
[實作概念說明]
1.
依照需求,class BBB 裡面有一個加密程序 EncodeProcessOfBBB()
public class BBB
{
public void EncodeProcessOfBBB()
{
}
}
2.
加密程序需要使用外部的API,
因此先宣告一個 委派,表示輸入型態 為 Int, 回傳形態為 Int
=> public delegate int EncoderAPI(int input);
3.
把此委派 產生為物件
=> public EncoderAPI EncoderAPIfromOutSide;
4.
在加密程序中,使用此外部API,使用invoke 觸發
=>
public void EncodeProcessOfBBB()
{
Console.WriteLine("Start to run EncodeProcessOfBBB()");
Console.WriteLine("To call encoder API from outside");
EncoderAPIfromOutSide.Invoke(5);
Console.WriteLine("Finish -EncodeProcessOfBBB");
}
最後附上完整程式碼,各位可自己貼到 C# console 專案執行
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System.Text; | |
using System.Threading.Tasks; | |
namespace DelegatesTest | |
{ | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
AAA insAAA = new AAA(); | |
Console.ReadLine(); | |
} | |
} | |
public class AAA | |
{ | |
public AAA() | |
{ | |
BBB insBBB = new BBB(); | |
insBBB.EncoderAPIfromOutSide = EncoderMethodofAAA; | |
insBBB.EncodeProcessOfBBB(); | |
} | |
public int EncoderMethodofAAA(int input) | |
{ | |
Console.WriteLine("==> EncoderMethodofAAA, the input value = " + input.ToString()); | |
return input; | |
} | |
} | |
public class BBB | |
{ | |
public delegate int EncoderAPI(int input); | |
public EncoderAPI EncoderAPIfromOutSide; | |
public void EncodeProcessOfBBB() | |
{ | |
Console.WriteLine("Start to run EncodeProcessOfBBB()"); | |
Console.WriteLine("To call encoder API from outside"); | |
EncoderAPIfromOutSide.Invoke(5); | |
Console.WriteLine("Finish -EncodeProcessOfBBB"); | |
} | |
} | |
} |