当前位置: 移动技术网 > IT编程>开发语言>.net > .Net——Func()与Action()

.Net——Func()与Action()

2018年04月21日  | 移动技术网IT编程  | 我要评论

plot.log,索菲尔,通金视频

 

 

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

 

 

 

 

           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";
            }

 

 

 

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

 

 

 

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

 

 

接着是func和action:

 

 

 

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

                    string strName = "lhc";
                    Action 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 funHello = HelloMM;
                    //Console.WriteLine(funHello("lhc"));

        #endregion
              

 

 

 

F12下,看下函数原型:

 

 

 

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

 

 

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

 

而对于func:

 

 

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


 

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

 

 

 

 

 

 

 

 

 

 

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网