C# delegate、event、Action、Func使用案例解析

2023-05-16

C# 中 delegate、event、Action、Func使用案例解析

一:delegate与event配合使用

public static class Evt_Test
    {
        public static string strEquals(string str1, string str2)
        {
            Console.WriteLine(str1 + str2);
            return str1.Concat(str2).ToString();
        }
    }

定义委托以及事件 

  private delegate void del_handler();
  private static event del_handler evt_handler;

调用

static void Main(string[] args)
        {
            evt_handler += new del_handler(() => Evt_Test.strEquals("s", "dedee"));
            evt_handler.Invoke();
            Console.ReadKey();
        }

二:Action与Event

         Action是无返回值的泛型委托。

   Action 表示无参,无返回值的委托

   Action<int,string> 表示有传入参数int,string无返回值的委托

   Action<int,string,bool> 表示有传入参数int,string,bool无返回值的委托

       Action<int,int,int,int> 表示有传入4个int型参数,无返回值的委托

   Action至少0个参数,至多16个参数,无返回值。

 //定义 
 private static event Action evt_Handler;

 //调用
  static void Main(string[] args)
        {
            evt_Handler += new Action(Evt_Test.Testing);
            evt_Handler?.Invoke();
            Console.ReadKey();
        }

//方法
  public static class Evt_Test
    {

        public static void Testing()
        {
            Console.WriteLine("testing");
        }
    }

三: Event与Func案例解析

C#中Fun和前面介绍过的Action有点类似,都是一个委托方法 , 不同的是Func是有返回值的,而Action没有

Fun常用有两个参数,前面的是输入参数,后面的是输出参数(意味着是在另一部分运算中产生的)恰恰是整个方法的返回值

(T arg)代表的是和输出参数类型相同的方法名称(返回值的类型和Func输出参数类型相同)

Fnc最多有16个输入参数,有且只有一个输出参数

Func<TResult> function代表function函数的返回值得类型是TResult。

   private static event Func<int> evtHandler;

   static void Main(string[] args)
        {
            evtHandler += new Func<int>(() => Evt_Test.Mul(2, 3));
            evtHandler?.Invoke();
            Console.ReadKey();
        }

   public static class Evt_Test
    {
        public static int Mul(int i, int j)
        {
            Console.WriteLine(i * j);
            return i * j;
        }
    }

 以上为今天全部内容,概念性的东西比较少,请大家自行百度,若有不正之处,请大家斧正,感谢!!!

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

C# delegate、event、Action、Func使用案例解析 的相关文章

随机推荐