Func 委托

.NET Framework 4

此内容为质量更高的人工翻译。若想同时查看此页面和原始英文页面的内容,请单击首选项然后选择经典视图作为您的查看首选项。

封装一个具有一个参数并返回 TResult 参数指定的类型值的方法。

命名空间:  System
程序集:  mscorlib(在 mscorlib.dll 中)

语法

C#

public delegate TResult Func<in T, out TResult>(

         T arg

)

 

VB:

'声明

 

Public Delegate Function Func(Of In T, Out TResult) ( _

         arg As T _

) As TResult

类型参数

in T

此委托封装的方法的参数类型。

该类型参数是逆变的。即可以使用指定的类型或派生程度更低的类型。有关协变和逆变的更多信息,请参见泛型中的协变和逆变

out TResult

此委托封装的方法的返回值类型。

该类型参数是协变的。即可以使用指定的类型或派生程度更高的类型。有关协变和逆变的更多信息,请参见泛型中的协变和逆变

参数

arg

类型:T
此委托封装的方法的参数。

返回值

类型:TResult
此委托封装的方法的返回值。

备注

可以使用此委托表示一种能以参数形式传递的方法,而不用显式声明自定义委托。 封装的方法必须与此委托定义的方法签名相对应。 也就是说,封装的方法必须具有一个通过值传递给它的参数,并且必须返回值。

说明

若要引用具有一个参数并返回 void 的方法(或者要在 Visual Basic 中引用被声明为 Sub 而不是被声明为 Function 的方法),请改用泛型 Action<T> 委托。

在使用 Func<T, TResult> 委托时,不必显式定义一个封装只有一个参数的方法的委托。 例如,以下代码显式声明了一个名为 ConvertMethod 的委托,并将对 UppercaseString 方法的引用分配给其委托实例。

C#

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();

   }

}

VB

' Declare a delegate to represent string conversion method

Delegate Function ConvertMethod(ByVal inString As String) As String

 

Module DelegateExample

   Public Sub Main()

      ' Instantiate delegate to reference UppercaseString method

      Dim convertMeth As ConvertMethod = AddressOf UppercaseString

      Dim name As String = "Dakota"

      ' Use delegate instance to call UppercaseString method

      Console.WriteLine(convertMeth(name))

   End Sub

 

   Private Function UppercaseString(inputString As String) As String

      Return inputString.ToUpper()

   End Function

End Module

 

以下示例简化了此代码,它所用的方法是实例化 Func<T, TResult> 委托,而不是显式定义一个新委托并将命名方法分配给该委托。

C#

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();

   }

}

VB

Module GenericFunc

   Public Sub Main()

      ' Instantiate delegate to reference UppercaseString method

      Dim convertMethod As Func(Of String, String) = AddressOf UppercaseString

      Dim name As String = "Dakota"

      ' Use delegate instance to call UppercaseString method

      Console.WriteLine(convertMethod(name))

   End Sub

 

   Private Function UppercaseString(inputString As String) As String

      Return inputString.ToUpper()

   End Function

End Module

您也可以按照以下示例所演示的那样在 C# 中将 Func<T, TResult> 委托与匿名方法一起使用。 (有关匿名方法的简介,请参见匿名方法(C# 编程指南)。)

C#

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> 委托 (有关 lambda 表达式的简介,请参见 lambda 表达式 Lambda 表达式(C# 编程指南)。)

C#

 

using System;

 

public class LambdaExpression

{

   public static void Main()

   {

      Func<string, string> convert = s => s.ToUpper();

 

      string name = "Dakota";

      Console.WriteLine(convert(name));  

   }

}

VB

Module LambdaExpression

   Public Sub Main()

      Dim convert As Func(Of String, String) = Function(s) s.ToUpper()

 

      Dim name As String = "Dakota"

      Console.WriteLine(convert(name)) 

   End Sub

End Module

Lambda 表达式的基础类型是泛型 Func 委托之一。 这样能以参数形式传递 lambda 表达式,而不用显式将其分配给委托。 尤其是,因为 System.Linq 命名空间中许多类型方法具有 Func<T, TResult> 参数,因此可以给这些方法传递 lambda 表达式,而不用显式实例化 Func<T, TResult> 委托。

示例

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

C#

using System;

using System.Collections;

using System.Collections.Generic;

using System.Linq;

 

static class Func

{

   static void Main(string[] args)

   {

      // Declare a Func variable and assign a lambda expression to the 

      // variable. The method takes a string and converts it to uppercase.

      Func<string, string> 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<String> 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

*/

VB

Imports System.Collections.Generic

Imports System.Linq

 

Module Func

   Public Sub Main()

      ' Declare a Func variable and assign a lambda expression to the 

      ' variable. The method takes a string and converts it to uppercase.

      Dim selector As Func(Of String, String) = Function(str) str.ToUpper()

 

      ' Create an array of strings.

      Dim words() As String = { "orange", "apple", "Article", "elephant" }

      ' Query the array and select strings according to the selector method.

      Dim aWords As IEnumerable(Of String) = words.Select(selector)

 

      ' Output the results to the console.

      For Each word As String In aWords

         Console.WriteLine(word)

      Next

   End Sub

End Module

' This code example produces the following output:

'          

'   ORANGE

'   APPLE

'   ARTICLE

'   ELEPHANT

 

来自:http://msdn.microsoft.com/zh-cn/library/bb549151.aspx

 

### C#Func 委托的使用方法 `Func<T, TResult>` 是一种泛型委托,用于表示返回指定类型的值的方法。它可以接受零个或多个输入参数,并始终返回一个结果。这种灵活性使得 `Func` 成为了许多场景下的理想选择,比如 LINQ 查询表达式、Lambda 表达式的定义以及其他需要动态传入逻辑的地方。 以下是关于 `Func` 的一些核心概念及其用法: #### 定义与语法 `Func` 可以有多种形式,具体取决于其接收的参数数量和类型。它的基本形式如下所示: - `Func<TResult>`:无参并返回 `TResult` 类型的结果。 - `Func<T, TResult>`:带有一个 `T` 类型参数并返回 `TResult` 类型的结果。 - `Func<T1, T2, ..., TResult>`:带有多个参数并返回 `TResult` 类型的结果。 下面是一个简单的例子,展示了如何声明和使用 `Func<int, int>` 来计算平方数[^2]。 ```csharp // 定义一个 Func 委托,该委托接受一个整数作为参数并返回另一个整数 Func<int, int> square = (num) => num * num; // 调用 Func 并打印结果 Console.WriteLine(square(5)); // 输出 25 ``` 此代码片段中,我们利用 Lambda 表达式定义了一个名为 `square` 的 `Func` 实例,它接受一个整数值并将这个值乘以其本身再返回结果。 #### 复杂应用场景 当涉及到更复杂的业务逻辑时,`Func` 同样适用。例如,在数据筛选过程中可以通过传递自定义条件实现高度定制化的过滤操作。这里给出一个基于列表查找特定项的例子[^3]: ```csharp List<string> names = new List<string>() { "Alice", "Bob", "Charlie" }; // 创建一个 Func 委托来匹配名字长度大于等于5的情况 Func<string, bool> nameFilter = (name) => name.Length >= 5; // 使用 FindAll 方法配合上述 Func 进行过滤 var longNames = names.FindAll(nameFilter); foreach(var name in longNames){ Console.WriteLine(name); // 输出 Alice 和 Charlie } ``` 在这个案例里,通过将 `Func<string, bool>` 结合到集合类库中的扩展方法上,实现了更加简洁优雅的数据处理方式。 #### 匿名方法支持 除了显式命名外,还可以直接嵌套匿名函数或者 lambda 表达式于需调用处完成即时初始化工作流。这种方式尤其适合那些仅限局部范围使用的简单行为描述场合[^4]. ```csharp // 不单独赋值给变量而是立即执行 int result = new Func<int>(() => { Random rand = new Random(); return rand.Next(0, 10); })(); Console.WriteLine($"Random Number: {result}"); ``` 以上演示了无需提前注册即可临时构建小型功能模块的能力。 --- ### 总结 综上所述,`Func` 委托因其丰富的变体结构设计而成为现代 C# 编程不可或缺的一部分。无论是基础运算还是高级特性集成都离不开对其合理运用的理解掌握。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值