Func<T,TResult> 委托

您所在的位置:网站首页 《越夜越有机》 Func<T,TResult> 委托

Func<T,TResult> 委托

2023-11-29 08:36| 来源: 网络整理| 查看: 265

重点

命名空间:System 程序集:mscorlib.dll, System.Runtime.dll 必须返回一个值

提示:以下是本篇文章正文内容,下面案例可供参考

一、Func 委托是什么?

封装一个方法,该方法具有一个参数,且返回由 TResult 参数指定的类型的值

public delegate TResult Func(T arg);

T 为此委托封装的方法的参数类型。 TResult 为此委托封装的方法的返回值类型。

二、示例 1.常规用法

下面的示例演示如何声明和使用 Func 委托。 此示例声明一个 Func 变量,并为其分配一个 lambda 表达式,该表达式将字符串中的字符转换为大写。 然后将封装此方法的委托传递给 Enumerable.Select 方法,以将字符串数组中的字符串更改为大写。

代码如下(示例):

// Declare a Func variable and assign a lambda expression to the // variable. The method takes a string and converts it to uppercase. Func selector = str => str.ToUpper(); // Create an array of strings. string[] words = { "orange", "apple", "Article", "elephant" }; // Query the array and select strings according to the selector method. IEnumerable aWords = words.Select(selector); // Output the results to the console. foreach (String word in aWords) Console.WriteLine(word); /* This code example produces the following output: ORANGE APPLE ARTICLE ELEPHANT */

注解:使用此委托来表示一个方法,该方法可作为参数传递,而无需显式声明自定义委托。 封装的方法必须对应于由此委托定义的方法签名。 这意味着,封装的方法必须具有一个通过值传递给它的参数,并且必须返回一个值。若要引用一个方法,该方法具有一个参数并返回 void 的方法 Function ,请改用泛型 Action 委托。

2. lambda 表达式分配给 Func 委托

代码如下(示例):

Func convert = s => s.ToUpper(); string name = "Dakota"; Console.WriteLine(convert(name)); // This code example produces the following output: // // DAKOTA

Lambda 表达式的基础类型是一个泛型 Func 委托。 这样,便可以将 lambda 表达式作为参数传递,而无需将其显式分配给委托。 具体而言,因为命名空间中的许多类型的方法 System.Linq 都有 Func 参数,所以可以将这些方法传递给 lambda 表达式,而无需显式实例化 Func 委托。

总结

Func 委托

public delegate TResult Func(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8);

该方法具有八个参数,并返回 TResult 参数所指定的类型的值。还有9-16个参数的,简单点说就是有返回值的委托,必须返回一个值。日常使用中,用过两次基本就熟悉了,不用刻意记忆哈



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3