.NET 委派 是型別安全的方法參考,封裝具有特定簽名與回傳型別的方法。類似現實世界的「委託遞送」:您決定「做什麼事」(遞送產品)、「參數是什麼」(客戶地址)、「回傳什麼」(付款),實際執行時再指派具體承辦單位 (FedEx/UPS)。
// 定義委派型別:接受兩個 Object,回傳 Comparison 列舉
public delegate Comparison WhichIsSmaller(object obj1, object obj2);
// 列舉定義比較結果
public enum Comparison { TheFirst = 1, TheSecond = 2 }
public:公開存取範圍。delegate:宣告委派而非方法。Comparison:回傳型別,此處為自訂列舉。WhichIsSmaller:委派名稱。(object obj1, object obj2) 定義可封裝方法的簽名。public class Pair {
private object[] thePair = new object[2];
public Pair(object first, object second) { thePair[0]=first; thePair[1]=second; }
// 排序方法接受委派參數
public void Sort(WhichIsSmaller comparer) {
if (comparer(thePair[0], thePair[1]) == Comparison.TheSecond) {
object temp = thePair[0]; thePair[0] = thePair[1]; thePair[1] = temp;
}
}
public void ReverseSort(WhichIsSmaller comparer) {
if (comparer(thePair[0], thePair[1]) == Comparison.TheFirst) {
object temp = thePair[0]; thePair[0] = thePair[1]; thePair[1] = temp;
}
}
}
// Student 依姓名字母序比較
public class Student {
public string Name { get; private set; }
public Student(string name) { Name = name; }
public static Comparison WhichStudentIsSmaller(object o1, object o2) {
Student s1 = (Student)o1, s2 = (Student)o2;
return string.Compare(s1.Name, s2.Name) < 0 ? Comparison.TheFirst : Comparison.TheSecond;
}
}
// Dog 依體重比較
public class Dog {
public int Weight { get; private set; }
public Dog(int weight) { Weight = weight; }
public static Comparison WhichDogIsSmaller(object o1, object o2) {
Dog d1 = (Dog)o1, d2 = (Dog)o2;
return d1.Weight < d2.Weight ? Comparison.TheFirst : Comparison.TheSecond;
}
}
// Student 排序
var studentPair = new Pair(new Student("Jesse"), new Student("Stacey"));
var studentComparer = new Pair.WhichIsSmaller(Student.WhichStudentIsSmaller);
studentPair.Sort(studentComparer); // Jesse 排在前面
// Dog 排序
var dogPair = new Pair(new Dog(65), new Dog(12));
var dogComparer = new Pair.WhichIsSmaller(Dog.WhichDogIsSmaller);
dogPair.Sort(dogComparer); // 12kg 排在前面
new Delegate(Type.Method),無需實例,效率較高。new Delegate(instance.Method),需實例存在,可存取實例狀態,重複調用較高效(無需重複傳遞 this)。WhichIsSmaller multi = studentComparer + dogComparer; // 鏈結多個方法
multi += AnotherMethod; // 繼續鏈結
multi -= studentComparer; // 移除
依序調用鏈結清單中所有方法,最後一個方法的回傳值為整體回傳值。
// C# 2.0 匿名方法
Sort(delegate(object a, object b) { return Comparison.TheFirst; });
// C# 3.0+ Lambda
Sort((a, b) => Comparison.TheFirst);
委派是 .NET 事件模型、非同步程式設計、LINQ、泛型委派 (Func<T, TResult>/Action<T>) 等現代語言特性的基石,掌握其核心概念對 .NET 開發至關重要。