Func<T1,T2,TResult> 代理人

定義

2 つのパラメーターを持ち、 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<in T1,in T2,out TResult>(T1 arg1, T2 arg2) where T1 : allows ref struct where T2 : allows ref struct where TResult : allows ref struct;
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

このデリゲートがカプセル化するメソッドの 2 番目のパラメーターの型。

この型パラメーターは反変です。 つまり、指定した型、または弱い派生型のいずれかを使用することができます。 共変性および反変性の詳細については、「ジェネリックの共変性と反変性」をご覧ください。
TResult

このデリゲートがカプセル化するメソッドの戻り値の型。

この型パラメーターは共変です。 つまり、指定した型、または強い派生型のいずれかを使用することができます。 共変性および反変性の詳細については、「ジェネリックの共変性と反変性」をご覧ください。

パラメーター

arg1
T1

このデリゲートがカプセル化するメソッドの最初のパラメーター。

arg2
T2

このデリゲートがカプセル化するメソッドの 2 番目のパラメーター。

戻り値

TResult

このデリゲートがカプセル化するメソッドの戻り値。

次の例では、 Func<T1,T2,TResult> デリゲートを宣言して使用する方法を示します。 この例では、 Func<T1,T2,TResult> 変数を宣言し、 String 値と Int32 値をパラメーターとして受け取るラムダ式を割り当てます。 ラムダ式は、String パラメーターの長さが Int32 パラメーターの値と等しい場合、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

注釈

このデリゲートを使用すると、カスタム デリゲートを明示的に宣言せずにパラメーターとして渡すことができるメソッドを表すことができます。 カプセル化されたメソッドは、このデリゲートによって定義されているメソッド シグネチャに対応している必要があります。 つまり、カプセル化されたメソッドには 2 つのパラメーターが必要であり、それぞれが値によって渡され、値を返す必要があります。

2 つのパラメーターを持ち、void (F# では unit) を返すメソッドを参照するには (または、Functionとしてではなく、Sub として宣言されているVisual Basic)、代わりにジェネリック Action<T1,T2> デリゲートを使用します。

Func<T1,T2,TResult> デリゲートを使用する場合、2 つのパラメーターを持つメソッドをカプセル化するデリゲートを明示的に定義する必要はありません。 たとえば、次のコードは、 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

次の例に示すように、 Func<T1,T2,TResult> デリゲートを C# の匿名メソッドと共に使用できます。 (匿名メソッドの概要については、「 匿名メソッド」を参照してください)。

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

次の例に示すように、ラムダ式を Func<T1,T2,TResult> デリゲートに割り当てることもできます。 (ラムダ式の概要については、「 ラムダ式 (VB)ラムダ式 (C#)ラムダ式 (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

ラムダ式の基になる型は、ジェネリック Func デリゲートの 1 つです。 これにより、デリゲートに明示的に割り当てることなく、ラムダ式をパラメーターとして渡すことができます。 特に、 System.Linq 名前空間の型の多くのメソッドには Func<T1,T2,TResult> パラメーターがあるため、 Func<T1,T2,TResult> デリゲートを明示的にインスタンス化することなく、これらのメソッドにラムダ式を渡すことができます。

拡張メソッド

名前 説明
GetMethodInfo(Delegate)

指定したデリゲートによって表されるメソッドを表すオブジェクトを取得します。

適用対象

こちらもご覧ください