Func和Action都是一种委托,这是在3.5里面新增的。2.0里面我们使用委托是用Delegate,Func位于System.Core命名空间下,使用委托可以提升效率,例如在反射中使用就可以弥补反射所损失的性能。
Action<T>和Func<T,TResult>的功能是一样的,只是Action<T>没有返类型,
Func<T,T,Result>有参数,有返回类型,Action,则既没有返回也没有参数。
在C#开发环境下,选择Func,然后按下F12切换到此内容的定义处,则有:
namespace System
{
// 摘要:
// Encapsulates a method that has one parameter and returns a value of the type
// specified by the TResult parameter.
//
// 参数:
// arg:
// The parameter of the method that this delegate encapsulates.
//
// 类型参数:
// T:
// The type of the parameter of the method that this delegate encapsulates.
//
// TResult:
// The type of the return value of the method that this delegate encapsulates.
//
// 返回结果:
// The return value of the method that this delegate encapsulates.
public delegate TResult Func<T, TResult>(T arg);
}
其实,Func<T,TResult> 的表现形式还可以分为以下几种:
--------------------------------------------------------------------------------
1、Func<T,TResult>
2、Func<T,T1,TResult>
3、Func<T,T1,T2,TResult>
4、Func<T,T1,T2,T3,TResult>
5、Func<T,T1,T2,T3,T4,TResult>
--------------------------------------------------------------------------------
分别说一下各个参数的意义,TResult表示 委托所返回值 所代表的类型, T,T1,T2,T3,T4表示委托所调用的方法的参数类型。
但是如果我们需要所封装的方法不返回值,增么办呢?就使用Action!
可以使用 Action<T1, T2, T3, T4>委托以参数形式传递方法,而不用显式声明自定义的委托。封装的方法必须与此委托定义的方法签名相对应。也就是说,封装的方法必须具有四个均通过值传递给它的参数,并且不能返回值。(在 C# 中,该方法必须返回 void。在 Visual Basic 中,必须通过 Sub…End Sub 结构来定义它。)通常,这种方法用于执行某个操作。
使用方法和Func类似!
如果你有Pascal语言或者Delphi语言的使用经验,则更容易理解上面内容。因为这两种语言中都有函数(有返回类型,可能有零个或多个参数)与过程(无返回类型,可能有零个或多个参数)的定义。
很显然,如果要将 lambda 表达式与 Action<T1, T2, T3, T4> 委托一起使用,则必须丢弃返回值。
改自:http://space.itpub.net/14466241/viewspace-675101