码迷,mamicode.com
首页 > Web开发 > 详细

.Net——Func<>与Action<>

时间:2015-05-17 21:55:48      阅读:368      评论:0      收藏:0      [点我收藏+]

标签:.net   delegate   泛型   


       

            首先来先写几个测试函数:




<span style="font-size:14px;">           public delegate void SayHello(string strName);

            public static void Hello(string strName)
            {

                Console.WriteLine(strName + " ,hello");

            }

            public static void SayGoodNight(string strName) {

                Console.WriteLine(strName + ",goodnight");

            }


            public static string HelloMM(string strName) {

                return strName + ",hello";
            }</span>

               


         为了好理解,先来看delegage调用:



               

#region 使用delegate调用
                    //SayHello sayHello = new SayHello(Hello);
                    //sayHello("lhc");
 #endregion


        接着是func和action:



      

    #region 使用action
                    //Action<string> action = Hello;
                    //action("lhc");

                    string strName = "lhc";
                    Action<string> action;
                    if (strName == "lhc")
                    {
                        //action = delegate(string strname)
                        //{
                        //    Console.WriteLine(strname + ",hello");
                        //};

                        //action = a => Console.WriteLine(a+",hello");

                        action = Hello;//传入方法

                    }
                    else 
                    {
                        //action = a => Console.WriteLine(a+",goodnight");
                        action = SayGoodNight;
                    }
                    action("lhc");

        #endregion




        #region func调用
                    //Func<string, string> funHello = HelloMM;
                    //Console.WriteLine(funHello("lhc"));

        #endregion
              


       

               F12下,看下函数原型:



           

// 摘要:
    //     封装一个方法,该方法只有一个参数并且不返回值。
    //
    // 参数:
    //   obj:
    //     此委托封装的方法的参数。
    //
    // 类型参数:
    //   T:
    //     此委托封装的方法的参数类型。
    public delegate void Action<in T>(T obj);


            对于Action,是没有返回值的。


           而对于func:


            

 // 摘要:
    //     封装一个具有一个参数并返回 TResult 参数指定的类型值的方法。
    //
    // 参数:
    //   arg:
    //     此委托封装的方法的参数。
    //
    // 类型参数:
    //   T:
    //     此委托封装的方法的参数类型。
    //
    //   TResult:
    //     此委托封装的方法的返回值类型。
    //
    // 返回结果:
    //     此委托封装的方法的返回值。
    [TypeForwardedFrom("System.Core, Version=3.5.0.0, Culture=Neutral, PublicKeyToken=b77a5c561934e089")]
    public delegate TResult Func<in T, out TResult>(T arg);

 

              无论<>里面传入多少个泛型,最后都会跟着一个TResult作为函数的返回值。








            



.Net——Func<>与Action<>

标签:.net   delegate   泛型   

原文地址:http://blog.csdn.net/lhc1105/article/details/45796075

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!