您的位置:首页 > 其它

.Net——Func<>与Action<>

2015-05-17 21:09 190 查看
       

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

<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作为函数的返回值。

            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: