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

이 대리자로 캡슐화되는 메서드의 첫 번째 매개 변수 형식입니다.

이 형식 매개 변수는 반공변(Contravariant)입니다. 즉, 지정한 형식이나 더 적게 파생된 모든 형식을 사용할 수 있습니다. 공변성(Covariance) 및 반공변성(Contravariance)에 대한 자세한 내용은 제네릭의 공변성(Covariance) 및 반공변성(Contravariance)을 참조하세요.
T2

이 대리자로 캡슐화되는 메서드의 두 번째 매개 변수 형식입니다.

이 형식 매개 변수는 반공변(Contravariant)입니다. 즉, 지정한 형식이나 더 적게 파생된 모든 형식을 사용할 수 있습니다. 공변성(Covariance) 및 반공변성(Contravariance)에 대한 자세한 내용은 제네릭의 공변성(Covariance) 및 반공변성(Contravariance)을 참조하세요.
TResult

이 대리자로 캡슐화되는 메서드의 반환 값 형식입니다.

이 형식 매개 변수는 공변(Covariant)입니다. 즉, 지정한 형식이나 더 많게 파생된 모든 형식을 사용할 수 있습니다. 공변성(Covariance) 및 반공변성(Contravariance)에 대한 자세한 내용은 제네릭의 공변성(Covariance) 및 반공변성(Contravariance)을 참조하세요.

매개 변수

arg1
T1

이 대리자로 캡슐화되는 메서드의 첫 번째 매개 변수입니다.

arg2
T2

이 대리자로 캡슐화되는 메서드의 두 번째 매개 변수입니다.

반환 값

TResult

이 대리자로 캡슐화되는 메서드의 반환 값입니다.

예제

다음 예제에는 선언 및 사용 하는 방법을 보여 줍니다.는 Func<T1,T2,TResult> 위임 합니다. 이 예제에서는 선언를 Func<T1,T2,TResult> 변수는 람다 식을 할당 하 고는 String 값 및 Int32 매개 변수 값입니다. 람다 식을 반환 true 경우의 길이 String 매개 변수는 값 같음는 Int32 매개 변수입니다. 이 메서드를 캡슐화 하는 대리자가 이후에 문자열 배열에 대 한 필터 문자열에 대 한 쿼리에 사용 됩니다.

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

설명

사용자 지정 대리자를 명시적으로 선언 하지 않고 매개 변수로 전달할 수 있는 메서드를 나타내는이 대리자를 사용할 수 있습니다. 캡슐화 된 메서드에이 대리자에 의해 정의 되는 메서드 시그니처와 일치 해야 합니다. 즉, 캡슐화된 메서드에는 각각 값으로 전달되고 값을 반환해야 하는 두 개의 매개 변수가 있어야 합니다.

참고

두 개의 매개 변수가 있고 반환 void (unitF#)(또는 Visual BasicSub) 대신 제네릭 Action<T1,T2> 대리자를 사용하는 메서드를 Function참조합니다.

대리자를 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

사용할 수는 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 대리자입니다. 이 대리자를 명시적으로 할당 하지 않고 람다 식을 매개 변수로 전달할 수 있습니다. 특히 때문에 형식의 여러 메서드를 System.Linq 네임 스페이스 Func<T1,T2,TResult> 매개 변수를 하면 이러한 메서드는 람다 식을 전달할 수 명시적으로 인스턴스화하지 않고도 Func<T1,T2,TResult> 위임 합니다.

확장 메서드

GetMethodInfo(Delegate)

지정된 대리자가 나타내는 메서드를 나타내는 개체를 가져옵니다.

적용 대상

추가 정보