C# 多播委托 注意事项

委托的基本概念就不说了,我先简单说一下什么是多播委托。

包含多个方法的委托就是多播委托

简单地举了例子:

复制代码
delegate void MyDelegate();

        static void Main(string[] args)
        {

            MyDelegate my1 = Write;

            my1 += Read;

            Console.ReadLine();
        }

        static void Write() 
        {
            Console.WriteLine("Write this is using named method");
        }

        static void Read()
        {
            Console.WriteLine("Read this is using named method");
        }
复制代码

 

多播委托识别"+","+=","-","-=" 运算符,以从委托中删除或添加方法调用。

 

多播委托实际上就是多个委托的集合,如果在实行多播委托时,其中一个方法抛出异常,那么整个迭代都会停止。

复制代码
       delegate void MyDelegate();

        static void Main(string[] args)
        {
            try
            {
                MyDelegate my1 = Write;
                my1 += Read;
                my1();
            }
            catch(Exception) 
            {
                Console.WriteLine("Error caught");
            }

            Console.ReadLine();
        }

        static void Write() 
        {
            Console.WriteLine("Write this is using named method");
            throw new Exception("Err in Write");
        }

        static void Read()
        {
            Console.WriteLine("Read this is using named method");
            throw new Exception("Err in Read");
        }
复制代码

得到的结果是:

Write this is using named method

Error caught

为了避免这种方法,需要自己迭代列表。下面是修改后的代码

复制代码
        delegate void MyDelegate();

        static void Main(string[] args)
        {
           
            MyDelegate my1 = Write;
            my1 += Read;

            Delegate[] dls = my1.GetInvocationList();

            foreach (MyDelegate dl in dls)
            {
                try
                {
                    dl();
                }
                catch(Exception)
                {
                    Console.WriteLine("Error caught");
                }
            }

            Console.ReadLine();
        }

        static void Write() 
        {
            Console.WriteLine("Write this is using named method");
            throw new Exception("Err in Write");
        }

        static void Read()
        {
            Console.WriteLine("Read this is using named method");
            throw new Exception("Err in Read");
        }
复制代码

得到的结果是:

Write this is using named method

Error caught

Read this is using named method

Error caught

posted @   のんきネコ  阅读(294)  评论(0编辑  收藏  举报
编辑推荐:
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
点击右上角即可分享
微信分享提示