zoukankan      html  css  js  c++  java
  • c# 委托(Func、Action)

    以前自己写委托都用 delegate, 最近看组里的大佬们都用 Func , 以及 Action 来实现, 代码简洁了不少, 但是看得我晕晕乎乎。 花点时间研究一下,记录一下,以便后期的查阅。

    1、Func 用法 (封装方法,传入参数, 有返回值)

    Func<in T1, in T2, ..., out TResult> (T1, T2, ...)  

    封装一个方法,该方法有 (0 /1/2/3  ... 16)个参数,且返回由 TResult 参数指定的值的类型。

        public static void Main()
            {
                // 方法一: Func 相当于系统内置的 委托
                Func<int, int, string> method = Calculate;
    
                // 方法二: 调用 Lambda 方法实现, 更简洁
                Func<int, int, string> method_1 = (x, y) =>
                {
                    int val = x + y;
                    return string.Format("the calculate {0} plus {1} result is: {2}", x, y, val);
                };
    
                Console.WriteLine(method(3, 5));
                Console.WriteLine(method_1(10, 18));
                Console.ReadLine();
            }
    public static string Calculate(int x, int y) { int val = x + y; return string.Format("the calculate {0} plus {1} result is: {2}", x, y, val); }

    2、Action 用法 (封装一个方法, 传入参数, 无返回值)

     Action<T1, T2, T3, ...>(t1, t2, t3 ...)

    封装一个方法, 该方法传入 (0/1/2 ...) 个参数, 且不返回值。

         public static void Main()
            {
                Method_First("Hi, Here!");
                Method_First("Hi, There!");
    
                Console.ReadLine();
            }
    
            private static void Method_First(string y)
            {
                Action<string> method;
                method = x => { Console.WriteLine("the input message is: {0}", x); };
                method(y);
            }
    
            private static void Method_Sec(string y)
            {
                Action<string> method = x => { Console.WriteLine("the input message is : {0}", x); };
                method(y);
            }

    3. 委托的使用

    讲了两种不同情况的委托, 那么什么时候使用委托呢?

    根据官方文档,在以下情况下,请使用委托:

    • 当使用事件设计模式时。

    • 当封装静态方法可取时。

    • 当调用方不需要访问实现该方法的对象中的其他属性、方法或接口时。

    • 需要方便的组合。

    • 当类可能需要该方法的多个实现时。

    4. 在 Task 使用委托

    Task 表示一个异步操作。

         public static void Main()
            {
                // 启动方法1
                Task t = Task.Run(() => 
                {
                    Thread.Sleep(1000);
                    Console.WriteLine("First task finished time is:{0}", DateTime.Now.ToString());
                });
    
    
                // 方法2
                Task t_2 = Task.Factory.StartNew(() => {
                    Thread.Sleep(2000);
                    Console.WriteLine("second task finished time is:{0}", DateTime.Now.ToString());
                });
    
    
                // 方法 3
                Action action = () =>
                {
                    Thread.Sleep(3000);
                    Console.WriteLine("third task finished time is:{0}", DateTime.Now.ToString());
                };
                Task.Factory.StartNew(action).ContinueWith(thirdTask =>
                {
                    if (thirdTask.IsCompleted)
                    {
                        Console.WriteLine("the third task has finished");
                    }
                    else if (thirdTask.IsFaulted)
                    {
                        Console.WriteLine(thirdTask.Exception);
                    }
                });
    
                Console.WriteLine("main thread has end:{0}",DateTime.Now.ToString() );
    
                Console.ReadKey();
            }

    运行结果如下 : 

    main thread has end:2018-03-04 22:03:39
    First task finished time is:2018-03-04 22:03:40
    second task finished time is:2018-03-04 22:03:41
    third task finished time is:2018-03-04 22:03:42
    the third task has finished

  • 相关阅读:
    探索c#之Async、Await剖析
    探索C#之布隆过滤器(Bloom filter)
    探索C#之虚拟桶分片
    刷新本地的DNS缓存数据
    php取整函数ceil,floor,round,intval函数的区别
    这样顶级人生规划 ,想不成功都难
    全篇干货,10分钟带你读透《参与感》
    iOS审核秘籍】提审资源检查大法
    php如何遍历多维的stdClass Object 对象,php的转换成数组的函数只能转换外面一丛数组
    RDS MySQL 连接数满情况的处理
  • 原文地址:https://www.cnblogs.com/yaolin1228/p/8492122.html
Copyright © 2011-2022 走看看