C# 透過 System.Delegate 實現函式指標功能。委派封裝方法,包含:
委派具備物件導向、型別安全、可靠特性。
delegate void myDelegate(); // 無參數、無回傳
delegate long myDelegate(string mystring); // 字串參數、長整數回傳
myDelegate Operation = new myDelegate(methodName);
委派物件不可變(簽名固定),但可指向相同簽名的不同方法:
myDelegate Operation = new myDelegate(Add);
Operation = new myDelegate(Multiply); // 簽名相同才可
delegate long myDelegate(int i, int j);
myDelegate Operation = new myDelegate(Add);
long lresult = Operation(10, 20); // 像呼叫一般方法
using System;
public class DelegateClass
{
delegate long myDelegate(int i, int j);
public static void Main(string[] args)
{
myDelegate Operation = new myDelegate(MathClass.Add);
Console.WriteLine("Call to Add method through delegate");
long l = Operation(10, 20);
Console.WriteLine("Sum of 10 and 20 is " + l);
Console.WriteLine("Call to Multiply method thru delegate");
Operation = new myDelegate(MathClass.Multiply);
l = Operation(1639, 1525);
Console.WriteLine("1639 multiplied by 1525 equals " + l);
}
}
public class MathClass
{
public static long Add(int i, int j) => i + j;
public static long Multiply(int i, int j) => i * j;
}
輸出:
Call to Add method through delegate
Sum of 10 and 20 is 30
Call to Multiply method through delegate
1639 multiplied by 1525 equals 2499475