委託(泛型委託、lamda表達式、用委託進行窗體傳值、多播委託

爲什麼要使用委託?

將一個方法作爲參數傳遞給另一個方法。

委託概念

聲明一個委託類型

委託所指向的函數必須跟委託具有相同的簽名(參數和返回值=簽名

泛型委託

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

namespace _03
{
    public delegate int DelCompare<T>(T t1,T t2);
    class 泛型委託
    {
        public static void GenericGetMax()
        {
            //Int類型委託
            int[] nums1 = { 1, 5, 7, 8, 6, 4, 11 };
            int max1= GetMax<int>(nums1, (int t1, int t2) =>
                {
                    return t1 - t2;
                });
            //string 類型委託
            string[] num2 = { "dfasf", "afds", "fwerwrre" };
            string max2 = GetMax<string>(num2, (string s1, string s2) =>
            {
                return s1.Length - s2.Length;
            });
            Console.WriteLine(max2);
        }

        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;
        }
    }
}

lamda表達式

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

namespace _03
{
    public delegate void DelOne();
    public delegate void DelTwo(string name);
    public delegate string DelThree(string name);
    class lamda表達式
    {
        public static void Lamda()
        { 
            //lamda表達式其實就是匿名函數更爲簡單的一種寫法
            DelOne del1 = () => { };
            DelOne del1_1=delegate() { };

            DelTwo del2= (string name) => { };
            DelTwo del2_2= delegate(string name) { };

            DelThree del3 = (string name) => { return name; };
            DelThree del3_3=delegate(string name){return name;};

            List<int> list=new List<int>{5,4,8,7,9,6,3,4,69};
            list.RemoveAll(n => n<4);
            foreach (int item in list)
	    {
		   Console.WriteLine(item);
	    }
        }
    }
}

使用委託來進行窗體傳值

Form2:

public delegate void DelGetMes(string wrod);
    public partial class FrmDanLi : Form
    {
        public static DelGetMes _del;
        public FrmDanLi(DelGetMes del)
        {
              _del = del;
        }
            
        private void button2_Click(object sender, EventArgs e)
        {
            _del(textBox1.Text);
        }
    }

Form1:

private void button1_Click(object sender, EventArgs e)
        {
           new FrmDanLi(GetMes).Show();
        }

        public void GetMes(string word)
        {
            label1.Text = word;
        }


多播委託

委託不僅僅可以指向一個函數,可以指向多個函數。




發佈了25 篇原創文章 · 獲贊 1 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章