C#中Fun和前面介绍过的Action有点类似,都是一个委托方法
不同的是Func是有返回值的,而Action没有
Fun常用有两个参数,前面的是输入参数,后面的是输出参数(意味着是在另一部分运算中产生的)恰恰是整个方法的返回值
(T arg)代表的是和输出参数类型相同的方法名称(返回值的类型和Func输出参数类型相同)
Fnc最多有16个输入参数,有且只有一个输出参数
Func<TResult> function代表function函数的返回值得类型是TResult。
//
// 摘要:
// Encapsulates a method that has one parameter and returns a value of the type
// specified by the TResult parameter.To browse the .NET Framework source code for
// this type, see the Reference Source.
//
// 参数:
// arg:
// The parameter of the method that this delegate encapsulates.
//
// 类型参数:
// T:
// The type of the parameter of the method that this delegate encapsulates.This
// type parameter is contravariant. That is, you can use either the type you specified
// or any type that is less derived. For more information about covariance and contravariance,
// see Covariance and Contravariance in Generics.
//
// TResult:
// The type of the return value of the method that this delegate encapsulates.This
// type parameter is covariant. That is, you can use either the type you specified
// or any type that is more derived. For more information about covariance and contravariance,
// see Covariance and Contravariance in Generics.
//
// 返回结果:
// The return value of the method that this delegate encapsulates.
[TypeForwardedFrom("System.Core, Version=3.5.0.0, Culture=Neutral, PublicKeyToken=b77a5c561934e089")]
public delegate TResult Func<in T, out TResult>(T arg);
public void Test()
{
//1.
Func<string, int> func1 = MyMethodA;
Console.WriteLine(func1("feige"));
//2.
MyMethodB<string>(new Func<string, int>(MyMethodA), "feige");
//3
MyMethodB(new Func<string, int>(MyMethodA), "feige");
}
public int MyMethodA(string str)
{
if (string.IsNullOrEmpty(str))
return 0;
return 1;
}
public void MyMethodB<T>(Func<T, int> func, T t)
{
Console.WriteLine(func(t));
}