Func<T1,T2,TResult> 委托

定义

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

generic <typename T1, typename T2, typename TResult>
public delegate TResult Func(T1 arg1, T2 arg2);
public delegate TResult Func<in T1,in T2,out TResult>(T1 arg1, T2 arg2);
public delegate TResult Func<T1,T2,TResult>(T1 arg1, T2 arg2);
type Func<'T1, 'T2, 'Result> = delegate of 'T1 * 'T2 -> 'Result
Public Delegate Function Func(Of In T1, In T2, Out TResult)(arg1 As T1, arg2 As T2) As TResult 
Public Delegate Function Func(Of T1, T2, TResult)(arg1 As T1, arg2 As T2) As TResult 

类型参数

T1

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

这是逆变类型参数。 即,可以使用指定的类型,也可以使用派生程度较低的任何类型。 有关协变和逆变的详细信息,请参阅泛型中的协变和逆变
T2

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

这是逆变类型参数。 即,可以使用指定的类型,也可以使用派生程度较低的任何类型。 有关协变和逆变的详细信息,请参阅泛型中的协变和逆变
TResult

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

这是协变类型参数。 即,可以使用指定的类型,也可以使用派生程度较高的任何类型。 有关协变和逆变的详细信息,请参阅泛型中的协变和逆变

参数

arg1
T1

此委托封装的方法的第一个参数。

arg2
T2

此委托封装的方法的第二个参数。

返回值

TResult

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

示例

以下示例演示如何声明和使用 Func<T1,T2,TResult> 委托。 此示例声明一个变量,并为其分配一个 Func<T1,T2,TResult> lambda 表达式,该表达式采用值 StringInt32 值作为参数。 如果参数的String长度等于参数的值Int32,则 lambda 表达式将true返回。 封装此方法的委托随后在查询中用于筛选字符串数组中的字符串。

using System;
using System.Collections.Generic;
using System.Linq;

public class Func3Example
{
   public static void Main()
   {
      Func<String, int, bool> predicate = (str, index) => str.Length == index;

      String[] words = { "orange", "apple", "Article", "elephant", "star", "and" };
      IEnumerable<String> aWords = words.Where(predicate).Select(str => str);

      foreach (String word in aWords)
         Console.WriteLine(word);
   }
}
open System
open System.Linq

let predicate = Func<string, int, bool>(fun str index -> str.Length = index)

let words = [ "orange"; "apple"; "Article"; "elephant"; "star"; "and" ]
let aWords = words.Where predicate

for word in aWords do
    printfn $"{word}"
Imports System.Collections.Generic
Imports System.Linq

Public Module Func3Example

   Public Sub Main()
      Dim predicate As Func(Of String, Integer, Boolean) = Function(str, index) str.Length = index

      Dim words() As String = { "orange", "apple", "Article", "elephant", "star", "and" }
      Dim aWords As IEnumerable(Of String) = words.Where(predicate)

      For Each word As String In aWords
         Console.WriteLine(word)
      Next   
   End Sub
End Module

注解

可以使用此委托来表示可以作为参数传递的方法,而无需显式声明自定义委托。 封装的方法必须与此委托定义的方法签名相对应。 这意味着封装的方法必须有两个参数,每个参数都按值传递给它,并且必须返回一个值。

备注

若要引用具有两个参数的方法,并在 F#) (或 Visual Basic 中返回void (unit,该方法声明为FunctionSub) ,请改用泛型Action<T1,T2>委托。

使用 Func<T1,T2,TResult> 委托时,无需显式定义封装具有两个参数的方法的委托。 例如,以下代码显式声明命名 ExtractMethod 的委托,并将对方法的 ExtractWords 引用分配给其委托实例。

using System;

delegate string[] ExtractMethod(string stringToManipulate, int maximum);

public class DelegateExample
{
   public static void Main()
   {
      // Instantiate delegate to reference ExtractWords method
      ExtractMethod extractMeth = ExtractWords;
      string title = "The Scarlet Letter";
      // Use delegate instance to call ExtractWords method and display result
      foreach (string word in extractMeth(title, 5))
         Console.WriteLine(word);
   }

   private static string[] ExtractWords(string phrase, int limit)
   {
      char[] delimiters = new char[] {' '};
      if (limit > 0)
         return phrase.Split(delimiters, limit);
      else
         return phrase.Split(delimiters);
   }
}
type ExtractMethod = delegate of string * int -> string []

let extractWords (phrase: string) limit =
    let delimiters = [| ' ' |]
    if limit > 0 then
        phrase.Split(delimiters, limit)
    else
        phrase.Split delimiters

// Instantiate delegate to reference extractWords function
let extractMeth = ExtractMethod extractWords
let title = "The Scarlet Letter"

// Use delegate instance to call extractWords function and display result
for word in extractMeth.Invoke(title, 5) do
    printfn $"{word}"
' Declare a delegate to represent string extraction method
Delegate Function ExtractMethod(ByVal stringToManipulate As String, _
                                ByVal maximum As Integer) As String()

Module DelegateExample
   Public Sub Main()
      ' Instantiate delegate to reference ExtractWords method
      Dim extractMeth As ExtractMethod = AddressOf ExtractWords
      Dim title As String = "The Scarlet Letter"
      ' Use delegate instance to call ExtractWords method and display result
      For Each word As String In extractMeth(title, 5)
         Console.WriteLine(word)
      Next   
   End Sub

   Private Function ExtractWords(phrase As String, limit As Integer) As String()
      Dim delimiters() As Char = {" "c}
      If limit > 0 Then
         Return phrase.Split(delimiters, limit)
      Else
         Return phrase.Split(delimiters)
      End If
   End Function
End Module

以下示例通过实例化 Func<T1,T2,TResult> 委托而不是显式定义新委托并向其分配命名方法来简化此代码。

using System;

public class GenericFunc
{
   public static void Main()
   {
      // Instantiate delegate to reference ExtractWords method
      Func<string, int, string[]> extractMethod = ExtractWords;
      string title = "The Scarlet Letter";
      // Use delegate instance to call ExtractWords method and display result
      foreach (string word in extractMethod(title, 5))
         Console.WriteLine(word);
   }

   private static string[] ExtractWords(string phrase, int limit)
   {
      char[] delimiters = new char[] {' '};
      if (limit > 0)
         return phrase.Split(delimiters, limit);
      else
         return phrase.Split(delimiters);
   }
}
open System

let extractWords (phrase: string) limit =
    let delimiters = [| ' ' |]
    if limit > 0 then
        phrase.Split(delimiters, limit)
    else
        phrase.Split delimiters

// Instantiate delegate to reference extractWords function
let extractMethod = Func<string, int, string[]> extractWords
let title = "The Scarlet Letter"

// Use delegate instance to call extractWords function and display result
for word in extractMethod.Invoke(title, 5) do
    printfn $"{word}"
Module GenericFunc
   Public Sub Main()
      ' Instantiate delegate to reference ExtractWords method
      Dim extractMeth As Func(Of String, Integer, String()) = AddressOf ExtractWords
      Dim title As String = "The Scarlet Letter"
      ' Use delegate instance to call ExtractWords method and display result
      For Each word As String In extractMeth(title, 5)
         Console.WriteLine(word)
      Next   
   End Sub

   Private Function ExtractWords(phrase As String, limit As Integer) As String()
      Dim delimiters() As Char = {" "c}
      If limit > 0 Then
         Return phrase.Split(delimiters, limit)
      Else
         Return phrase.Split(delimiters)
      End If
   End Function
End Module

可以将委托与 C# 中的匿名方法配合使用 Func<T1,T2,TResult> ,如以下示例所示。 (有关匿名方法简介,请参阅 Anonymous Methods.)

using System;

public class Anonymous
{
   public static void Main()
   {
      Func<string, int, string[]> extractMeth = delegate(string s, int i)
         { char[] delimiters = new char[] {' '};
           return i > 0 ? s.Split(delimiters, i) : s.Split(delimiters);
         };

      string title = "The Scarlet Letter";
      // Use Func instance to call ExtractWords method and display result
      foreach (string word in extractMeth(title, 5))
         Console.WriteLine(word);
   }
}

还可以将 lambda 表达式分配给 Func<T1,T2,TResult> 委托,如以下示例所示。 (有关 lambda 表达式简介,请参阅 Lambda 表达式 (VB) Lambda 表达式 (C#) lambda 表达式 (F#) .)

using System;

public class LambdaExpression
{
   public static void Main()
   {
      char[] separators = new char[] {' '};
      Func<string, int, string[]> extract = (s, i) =>
           i > 0 ? s.Split(separators, i) : s.Split(separators) ;

      string title = "The Scarlet Letter";
      // Use Func instance to call ExtractWords method and display result
      foreach (string word in extract(title, 5))
         Console.WriteLine(word);
   }
}
open System

let separators = [| ' ' |]

let extract =
    Func<string, int, string []> (fun s i ->
        if i > 0 then
            s.Split(separators, i)
        else
            s.Split separators)

let title = "The Scarlet Letter"

// Use Func instance to call lambda expression and display result
for word in extract.Invoke(title, 5) do
    printfn $"{word}"
Module LambdaExpression
   Public Sub Main()
      Dim separators() As Char = {" "c}
      Dim extract As Func(Of String, Integer, String()) = Function(s, i) _
          CType(iif(i > 0, s.Split(separators, i), s.Split(separators)), String())  
      
      Dim title As String = "The Scarlet Letter"
      For Each word As String In extract(title, 5)
         Console.WriteLine(word)
      Next   
   End Sub
End Module

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

扩展方法

GetMethodInfo(Delegate)

获取指示指定委托表示的方法的对象。

适用于

另请参阅