委托(泛型委托、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万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章