前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >c# 委托(Func、Action)

c# 委托(Func、Action)

作者头像
用户2434869
发布2018-09-12 10:39:07
7.1K0
发布2018-09-12 10:39:07
举报
文章被收录于专栏:yl 成长笔记yl 成长笔记

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

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

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

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

代码语言:javascript
复制
    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 ...) 个参数, 且不返回值。

代码语言:javascript
复制
     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 表示一个异步操作。

代码语言:javascript
复制
     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

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2018-03-04 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档