1.泛型委託,返回參數傳T,參數傳一個委託類型的參數TResult
class Program {
public delegate int DelCompare<T>(T t1, T t2);static void Main(string[] args)
{ int[] nums = { 1, 2, 3, 4, 5 };
int max = GetMax<int>(nums, Compare1);
Console.WriteLine(max);
string[] names = { "abcdefg", "fdsfds", "fdsfdsfdsfdsfdsfdsfdsfsd" };
string max1 = GetMax<string>(names, (string s1, string s2) => {
return s1.Length - s2.Length; });
Console.WriteLine(max1);
Console.ReadKey(); }
public static T GetMax<T>(T[] nums, DelCompare<T> del) {
T max = nums[0];
for (int i = 0; i < nums.Length; i++) {
//要傳一個比較的方法
if (del(max, nums[i]) < 0) {
max = nums[i]; } }
return max; }
public static int Compare1(int n1, int n2) { return n1 - n2; } }
2.總共3種委託形式delegate、Action、Func<TResult>已經定義好的泛型委託,窗體傳值就使用委託,Action無返回值的委託HMGNV-WCYXV-X7G9W-YCX63-B98R2
3、多播委託
一個委託指向多個方法,執行委託類型的對象時,它指向的方法一起執行
public delegate void DelTest();
DelTest method=Test1;
method+=Test2;
method+=Test3;
method();//一起執行3個方法
public void Test1()
{
Console.Write("T1");
}
public void Test2()
{
Console.Write("T2");
public void Test3()
{
Console.Write("T3");