Func<T, TResult> 委托其实与[button url="http://redcat7.net/?p=340" style="dark"]Action<T> 委托[/button]一样,都是为了简化委托的使用,这两者的不同之处在于Action<T> 封装一个方法且该方法只有一个参数并且不返回值,而Func<T, TResult>封装一个具有一个参数并返回 TResult 参数指定的类型值的方法。
使用Func<T, TResult> 委托表示一种能以参数形式传递的方法,而不用显式声明自定义委托。 封装的方法必须与此委托定义的方法签名相对应。 也就是说,封装的方法必须具有一个通过值传递给它的参数,并且必须返回值。
在使用 Func<T, TResult> 委托时,不必显式定义一个封装只有一个参数的方法的委托。 例如,以下代码显式声明了一个名为 ConvertMethod 的委托,并将对 UppercaseString 方法的引用分配给其委托实例,这是这是传统的委托使用方式。
using System; delegate string ConvertMethod(string inString); public class DelegateExample { public static void Main() { // Instantiate delegate to reference UppercaseString method ConvertMethod convertMeth = UppercaseString; string name = "Dakota"; // Use delegate instance to call UppercaseString method Console.WriteLine(convertMeth(name)); } private static string UppercaseString(string inputString) { return inputString.ToUpper(); } }
以下示例简化了此代码,它所用的方法是实例化 Func<T, TResult> 委托,而不是显式定义一个新委托并将命名方法分配给该委托。
using System; public class GenericFunc { public static void Main() { // Instantiate delegate to reference UppercaseString method Func<string, string> convertMethod = UppercaseString; string name = "Dakota"; // Use delegate instance to call UppercaseString method Console.WriteLine(convertMethod(name)); } private static string UppercaseString(string inputString) { return inputString.ToUpper(); } }
我们也可以按照以下示例所演示的那样在 C# 中将 Func<T, TResult> 委托与匿名方法一起使用。
using System; public class Anonymous { public static void Main() { Func<string, string> convert = delegate(string s) { return s.ToUpper();}; string name = "Dakota"; Console.WriteLine(convert(name)); } }
我们还可以按照以下示例所演示的那样将 lambda 表达式分配给 Func<T, TResult> 委托。
using System; public class LambdaExpression { public static void Main() { Func<string, string> convert = s => s.ToUpper(); string name = "Dakota"; Console.WriteLine(convert(name)); } }
原文:http://www.cnblogs.com/hzzhao/p/5264681.html