C#---委托与事件

部分内容由千峰教育(莫新宇)听课笔记总结

 委托就是用来储存方法的结构

 delegate  返回值类型  委托类型名(参数列表);

例如:delegate House BuyHouseEventHandle(float money, float area);  其中House为返回值,而float money, float area为参数

委托的返回值和参数列表与类中的内容一致

---------------------------------------------------------------------------------------------

using System;

namespace t1
{
    //创建委托类型
    delegate void HelpFindHouseEventHandle(float money, float area);
    class Lianjia 
    {   void SayHello() { 
            
        }
        public void HelpFindHouse(float money, float area) {
            Console.WriteLine("链家在帮忙找房子");
        }    
    }
    class WoAiWoJia 
    {
        public void HelpFindHouse(float money, float area) {
            Console.WriteLine("我爱我家在帮忙找房子");
        }
    }
    class MaiTian {
        public void HelpFindHouse(float money, float area) {
            Console.WriteLine("麦田在帮忙找房子");
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            //委托对象
            HelpFindHouseEventHandle hfe;
            Lianjia lianjia = new Lianjia();
            WoAiWoJia woAiWoJia = new WoAiWoJia();
            MaiTian maiTian = new MaiTian();
            hfe = lianjia.HelpFindHouse;
            hfe += woAiWoJia.HelpFindHouse;
            hfe += maiTian.HelpFindHouse;
            hfe(1000000,200);
        }
    }
}

--------------------------------------------------------------------------------------------

using System;

namespace t1
{
    //创建委托类型
    delegate void HelpFindHouseEventHandle(float money, float area);
    class Lianjia 
    {   void SayHello() { 
            
        }
        public void HelpFindHouse(float money, float area) {
            Console.WriteLine("链家在帮忙找房子");
        }    
    }
    class WoAiWoJia 
    {
        public void HelpFindHouse(float money, float area) {
            Console.WriteLine("我爱我家在帮忙找房子");
        }
    }
    class MaiTian {
        public void HelpFindHouse(float money, float area) {
            Console.WriteLine("麦田在帮忙找房子");
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            //委托对象
            HelpFindHouseEventHandle hfe;
            HelpFindHouseEventHandle newHfe;
            Lianjia lianjia = new Lianjia();
            WoAiWoJia woAiWoJia = new WoAiWoJia();
            MaiTian maiTian = new MaiTian();
            hfe = lianjia.HelpFindHouse;
            hfe += woAiWoJia.HelpFindHouse;
            hfe += maiTian.HelpFindHouse;//绑定
            newHfe = hfe;
            newHfe -= woAiWoJia.HelpFindHouse;//解除绑定
            newHfe -= maiTian.HelpFindHouse;
            hfe(1000000,200);
            Console.WriteLine("--------------------");
            newHfe(1000, 2);
        }
    }
}

----------------------------------------------------------------------------------------------

委托对象

先定义委托类型

delegate House BuyHouseEventHandle(float money, float area);

delegate 返回值类型  委托类型名(参数列表); 

[访问修饰符] 委托类型名称   委托对象的名称

public BuyHouseEventHandle buyHouseEventHandle;

给委托对象赋值

委托对象=方法名;

xiaoming.buyHoueEventHandle=intermediary.BuyHouse;//注意只写方法名,没有括号

Tips:委托对象,保存的是方法的内存地址

委托对象的执行

委托对象(参数列表);

House house=xiaoming.buyHouseEventHandle(1000000,80);

Tips:委托对象为空时能不能执行的,执行前提前判断

---------------------------------------------------------------------------------

using System;

namespace t1
{
    //创建委托类型
    delegate void HelpFindHouseEventHandle(float money, float area);
    delegate void TestEventHandle<T>(T para);
    delegate void EmptyEventHandle();
    delegate void NewEmptyEventHandle();
    class Lianjia 
    {   public void Fighting<T>(T words) {
            Console.WriteLine("链家员工正在喊口号:"+words);
        }
        void SayHello() {
            Console.WriteLine("链家员工正在Say Hello");
        }
        public void HelpFindHouse(float money, float area) {
            Console.WriteLine("链家在帮忙找房子");
        } 
    }
    class WoAiWoJia 
    {
        public void HelpFindHouse(float money, float area) {
            Console.WriteLine("我爱我家在帮忙找房子");
        }
    }
    class MaiTian {
        public void HelpFindHouse(float money, float area) {
            Console.WriteLine("麦田在帮忙找房子");
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            //委托对象
            HelpFindHouseEventHandle hfe;
            HelpFindHouseEventHandle newHfe;
            Lianjia lianjia = new Lianjia();
            WoAiWoJia woAiWoJia = new WoAiWoJia();
            MaiTian maiTian = new MaiTian();
            hfe = lianjia.HelpFindHouse;
            hfe += woAiWoJia.HelpFindHouse;
            hfe += maiTian.HelpFindHouse;
            newHfe = hfe;
            newHfe -= woAiWoJia.HelpFindHouse;
            newHfe -= maiTian.HelpFindHouse;
            hfe(1000000,200);
            Console.WriteLine("--------------------");
            newHfe(1000, 2);
            //创建一个委托对象
            TestEventHandle<string> testEventHandle;
            //给委托对象赋值,存储链家喊口号的方法
            testEventHandle = lianjia.Fighting;
            testEventHandle("我最棒!");
            TestEventHandle<int> intEventHandle;
            intEventHandle = lianjia.Fighting;
            intEventHandle(123);
        }
    }
}
--------------------------------------------------------------------------------------------------

系统委托类型

无返回值系统委托Action<>

有返回值系统委托Func<>

--------------------------------------------------------------------------------------------------

using System;

namespace gSystemDelegate
{
    //创建委托类型
    delegate void SayEventHandle();
    class House { 
    
    }
    class Person {
        private string name;

        public Person(string name)
        {
            this.name = name;
        }
        public House BuyHouse(float money, float area, string address) {
            Console.WriteLine($"{name}正在买房子。。。");
            Console.WriteLine($"{name}买房子需求:\n面积:{area}平米,预算:{money},地址:{address}...");
            return null;
        }
        public void SayHello() {
            Console.WriteLine($"{name}:SayHello");
        }
        public void Say(string words) {
            Console.WriteLine($"{name}正在讲话:{words}");
        }
        //获取姓名
        public string GetName() {
            Console.WriteLine($"{name}正在返回姓名");
            return name;
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            //创建委托对象
            SayEventHandle sayEventHandle;
            Person xiaoming = new Person("小明");
            //给委托对象赋值
            sayEventHandle = xiaoming.SayHello;
            sayEventHandle();
            Action action;
            action = xiaoming.SayHello;
            action();
            Action<string> stringAction;
            stringAction = xiaoming.Say;
            stringAction("你好厉害!");
            Func<string> func;
            func = xiaoming.GetName;
            //调用委托对象
            Console.WriteLine(func());
            //存储买房子方法该用哪一个委托类型呢?
            Func<float, float, string, House> houseFunc;
            //给委托类型赋值
            houseFunc = xiaoming.BuyHouse;
            //调用委托
            House house=houseFunc(20000000,400,"北京五环");

        }
    }
}

--------------------------------------------------------------------------------------------------

匿名函数

匿名函数就是没有函数名的函数

匿名函数仅限委托绑定

普通匿名函数方式绑定

委托对象+=delegate([参数列表]){//方法体}

xiaoming.buyHouseEventHandle+=delegate(float m, float a){Console.WriteLine("匿名中介在帮忙找房子")};return null;};

-----------------------------------------------------------------------------------------------

using System;

namespace hAnonymityMethod
{
    class Person {
        public Action<string> stringAction;
        private string name;
        private int age;

        public Person(string name, int age)
        {
            this.name = name;
            this.age = age;
        }
        public void ReadWords(string words) {
            Console.WriteLine("朗读英文文章");
            if (stringAction!=null) {
                stringAction(words);
            }
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Person xiaoming = new Person("xiaoming",15);
            xiaoming.stringAction = delegate (string str)
            {
                Console.WriteLine("在Main中朗读文章");
                Console.WriteLine("文章内容:" + str);
            };
            xiaoming.ReadWords("Hello World...");
        }
    }
}

----------------------------------------------------------------------------------------------------

拉姆达表达式方式绑定

委托对象+=(参数列表)=>{ //方法体 }

xiaoming.buyHouseEvnetHandle+=(float m, float a)=>{Console.WriteLine("匿名拉姆达表达式");return null;};

-----------------------------------------------------------------------------------------------------

using System;

namespace hAnonymityMethod
{
    class Person {
        public Action<string> stringAction;
        private string name;
        private int age;

        public Person(string name, int age)
        {
            this.name = name;
            this.age = age;
        }
        public void ReadWords(string words) {
            Console.BackgroundColor = ConsoleColor.White;
            Console.BackgroundColor = ConsoleColor.Green;
            Console.WriteLine($"{name}朗读英文文章");
            Console.ResetColor();
            if (stringAction!=null) {
                stringAction(words);
            }
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Person xiaoming = new Person("xiaoming",15);
            xiaoming.stringAction = delegate (string str)
            {
                Console.WriteLine("在Main中朗读文章");
                Console.WriteLine("文章内容:" + str);
            };
            xiaoming.stringAction += (string words) => { Console.ForegroundColor = ConsoleColor.Magenta;
                //方法体
                Console.WriteLine("在拉姆达表达式中朗读文章");
                Console.WriteLine("文章内容:" + words);
                Console.ResetColor();
            };
            xiaoming.ReadWords("Hello World...");
        }
        public static void Read(string words) {
            //Console.BackgroundColor = ConsoleColor.White;
            Console.BackgroundColor = ConsoleColor.Red;
            Console.WriteLine("在静态函数中朗读文章");
            Console.WriteLine("文章内容"+words);
            Console.ResetColor();
        }
    }
}

 回调函数

回调给的是方法

public void Marry(BuyHouseEventHandle buyHourse){

        if(buyHouse==null){Console.WriteLine("No!!!!");}

        else{buyHouse(1000000,200);Console.WriteLine("有房子啦,我好幸福!");}}

xiaomei.Marry(intermediary.BuyHouse);

-------------------------------------------------------------------------------------------------------------

using System;
using System.Collections.Generic;

namespace iCallBack
{
    class Person {
        private string name;
       

        public Person(string name)
        {
            this.name = name;
        }
      

        //设置联系方式
        public void SetRelationFunction(string name, Action<string> relationFun) {
            Console.WriteLine($"{name}已经将联系方式给了:"+this.name);
            Console.WriteLine("a few later...");
            relationFun(this.name);//委托方法
        }
        public void CallMe(string name) {
            Console.ForegroundColor = ConsoleColor.Yellow;
            Console.WriteLine($"我是{this.name}...");
            Console.WriteLine($"{name}正在Call Me...");
            Console.WriteLine("联系建立...Chating...");
            Console.ResetColor();
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Person xiaoming = new Person("小明");
            Person xiaohong = new Person("小红");
            xiaohong.SetRelationFunction("小明",xiaoming.CallMe);

        }
    }
}

代码解析:  xiaohong.SetRelationFunction("小明",xiaoming.CallMe);xiaoming.CallMe为委托对象(通过类.方法调用),作为SetRelationFunction(string name, Action<string> relationFun)的参数。relationFun(this.name);//委托方法 与CallMe(string name)参数一致,并调用该方法。

----------------------------------------------------------------------------------------------------------

using System;
using System.Collections.Generic;

namespace iCallBack
{
    class Person {
        private string name;
        //电话本
        private Dictionary<string, Action<string>> relationBook;

        public Person(string name)
        {
            this.name = name;
            relationBook = new Dictionary<string, Action<string>>();
        }
      

        //设置联系方式
        public void SetRelationFunction(string name, Action<string> relationFun) {
            Console.WriteLine($"{name}已经将联系方式给了:"+this.name);
            //将联系方式添加到电话本
            relationBook.Add(name, relationFun);//relationFun依旧时委托
        }
        public void CallSomeOne(string name) {
            if (relationBook.ContainsKey(name))
            {
                Console.WriteLine($"{this.name}正在打电话联系{name}");
                relationBook[name](this.name);
            }
            else {
                Console.WriteLine($"电话本中没有找到{name}的电话号码");
            }
        }
        public void CallMe(string name) {
            Console.ForegroundColor = ConsoleColor.Yellow;
            Console.WriteLine($"{name}正在联系{this.name}...");
            Console.WriteLine("联系建立...Chating...");
            Console.ResetColor();
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Person xiaoming = new Person("小明");
            Person xiaohong = new Person("小红");
            xiaohong.SetRelationFunction("小明",xiaoming.CallMe);
            Console.WriteLine("Main...A Few later");
            xiaohong.CallSomeOne("小明");

        }
    }
}

代码解析:Main方法中代码执行顺序,xiaohong的SetRelationFunction执行,由relationBook.Add(name, relationFun);将“小明”及代理方法(CallMe)储存到字典。当使用xiaohong.CallSomeOne("小明")时,打印小红正在打电话联系小明。通过字典调用小明的委托代理。

 

----------------------------------------------------------------------------------------------------------

 事件(特殊的委托对象)

[访问修饰符]event 委托类型 事件名称

public event BuyHouseEventHandle buyHouseEvent;

在非时间所在的类中,只能对事件进行绑定(+=)和解绑定(-=)

在事件所在的类中,可以对事件进行赋值(=)、调用、绑定(+=)和解绑定(-=)

using System;

namespace jEvent
{
    //声明委托类型
    delegate void EmptyEventHandle();
    class Person
    {
        private string name;

        public Person(string name)
        {
            this.name = name;
        }

        public event EmptyEventHandle sayHelloEvent;
        public void Test() {
            //赋值委托对象
            sayHelloEvent = SayHello;
            //给事件对象绑定方法
            sayHelloEvent += SayHello;
            //给事件对象解除绑定方法
            sayHelloEvent -= SayHello;
            //执行事件
            sayHelloEvent();
        }
        void SayHello() {
            Console.WriteLine($"{name}在SayHello");
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Person xiaoming = new Person("Xiaoming");
            xiaoming.Test();
            MainTest(xiaoming);
        }
        public static void MainTest(Person person) { person.sayHelloEvent += SayHello; }//不可以直接‘=’
        public static void SayHello() { Console.WriteLine("在MainClass中SayHello"); }
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值