• 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

  • 相关阅读:
    2019春季第五周作业
    2019春第四周作业(基础题)计算机
    2019第三周作业
    第二周基础作业
    2019春第九周作业
    2019年春第八周作业
    第七周总结
    第六周作业
    2019春第五周作业
    2019年春季学期第四周作业
  • 原文地址:https://www.cnblogs.com/yaolin1228/p/8492122.html
Copyright © 2020-2023  润新知