• c#' 回调函数、委托 事件、委托链异常


    回调函数:  当一个函数执行完,执行作为参数传进来的函数。 通常是通过函数指针来调用。当函数执行完,将指针地址作为参数传递给另一个函数,这个指针被用来调用所指向的函数,称之为回调函数。

    委托(delegate):委托的本质就是一个回调函数帆软封装。

    事件(event): 事件的本质其实是对委托的封装,因为c# 是一门自举语言,通过il 反编译器可以看到,event 最后会强制转化为 delegate 。所以说事件是一种特殊的委托,而且性能较差

    性能 :event<委托<回调函数

    // 委托链异常

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading;
    using System.Threading.Tasks;
    
    namespace 委托和事件
    {
    
    
        public class EventBus
        {
            public static Action<string> Actions = null;
    
            public delegate void  @delegate(string name);
            public static @delegate mdelegate;
            public void SendMessage()
            {
                if (Actions != null)
                {
                    // 获取actions 中的action列表
                   var actiones=  Actions.GetInvocationList();
                    foreach (var item  in actiones)
                    {
    
                        var ac = (Action<string>)item;
                        ac.Invoke("sendMessage from EventBus");
                    }
    
                    // 这种方式,如果有一个委托发生异常,则后面的委托将停止执行,所以选择以上方式
                   // Actions.Invoke("sendMessage from EventBus");
                }
                if (mdelegate != null)
                {    // myDelegates 中的Delegate列表
                    Delegate[] myDelegates = mdelegate.GetInvocationList();
                    foreach (var item in myDelegates)
                    {
                        var de = (@delegate)item;
                        try
                        {
                            de("sssssssssssssssssss");
                        }
                        catch(Exception ex)
                        {
                            Console.WriteLine($"--{ex}");
                        }
                    }
    
                    // 这种方式,如果有一个委托发生异常,则后面的委托将停止执行,所以选择以上方式,用foreach
                    // mdelegate("11111111111");
                }
    
    
    
            }
           
        }
    }
    

      

  • 相关阅读:
    HTML事件处理程序---内联onclick事件
    js的width函数
    了解跨站请求伪造CSRF
    离线百度地图
    GetOverlappedResult 函数
    OVERLAPPED 结构
    SetupDi系列函数
    Linux 各个命令的缩写原型
    Linux grep命令
    Linux if[......] then ......else...... fi
  • 原文地址:https://www.cnblogs.com/hnzheng/p/12777245.html
Copyright © 2020-2023  润新知