Func<T,TResult> 대리자

정의

매개 변수가 하나이고 TResult 매개 변수에 지정된 형식의 값을 반환하는 메서드를 캡슐화합니다.

generic <typename T, typename TResult>
public delegate TResult Func(T arg);
public delegate TResult Func<in T,out TResult>(T arg);
public delegate TResult Func<T,TResult>(T arg);
type Func<'T, 'Result> = delegate of 'T -> 'Result
Public Delegate Function Func(Of In T, Out TResult)(arg As T) As TResult 
Public Delegate Function Func(Of T, TResult)(arg As T) As TResult 

형식 매개 변수

T

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

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

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

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

매개 변수

arg
T

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

반환 값

TResult

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

예제

다음 예제에는 선언 및 사용 하는 방법을 보여 줍니다.는 Func<T,TResult> 위임 합니다. 이 예에서는 변수를 선언 Func<T,TResult> 하 고 문자열의 문자를 대문자로 변환 하는 람다 식을 할당 합니다. 이 메서드를 캡슐화 하는 대리자는 나중에 메서드에 전달 되어 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<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

*/
open System
open System.Linq

// Declare a Func variable and assign a lambda expression to the
// variable. The function takes a string and converts it to uppercase.
let selector = Func<string, string>(fun str -> str.ToUpper())

// Create a list of strings.
let words = [ "orange"; "apple"; "Article"; "elephant" ]

// Query the list and select strings according to the selector function.
let aWords = words.Select selector

// Output the results to the console.
for word in aWords do
    printfn $"{word}"

// This code example produces the following output:
//     ORANGE
//     APPLE
//     ARTICLE
//     ELEPHANT
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
// Declare a delegate
delegate String ^ MyDel(String ^);

// Create wrapper class and function that takes in a string and converts it to uppercase
ref class DelegateWrapper {
public:
    String ^ ToUpper(String ^ s) {
        return s->ToUpper();
    }
};

int main() {
    // Declare delegate
    DelegateWrapper ^ delegateWrapper = gcnew DelegateWrapper;
    MyDel ^ DelInst = gcnew MyDel(delegateWrapper, &DelegateWrapper::ToUpper);

    // Cast into Func
    Func<String ^, String ^> ^ selector = reinterpret_cast<Func<String ^, String ^> ^>(DelInst);

    // Create an array of strings
    array<String ^> ^ words = { "orange", "apple", "Article", "elephant" };

    // Query the array and select strings according to the selector method
    Generic::IEnumerable<String ^> ^ aWords = Enumerable::Select((Generic::IEnumerable<String^>^)words, selector);

    // Output the results to the console
    for each(String ^ word in aWords)
        Console::WriteLine(word);
    /*
    This code example produces the following output:

    ORANGE
    APPLE
    ARTICLE
    ELEPHANT
    */
}

설명

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

참고

매개 변수가 하나이 고를 반환 하는 메서드를 참조 하는 경우 void (또는 Visual Basic이 아닌로 선언 된 Sub Function ) 경우 대신 제네릭 대리자를 사용 Action<T> 합니다.

대리자를 사용 하는 경우 Func<T,TResult> 단일 매개 변수를 사용 하 여 메서드를 캡슐화 하는 대리자를 명시적으로 정의할 필요가 없습니다. 예를 들어 다음 코드는 라는 대리자를 명시적으로 선언 하 ConvertMethod 고 메서드에 대 한 참조를 UppercaseString 해당 대리자 인스턴스에 할당 합니다.

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();
   }
}
type ConvertMethod = delegate of string -> string

let uppercaseString (inputString: string) =
    inputString.ToUpper()
    
// Instantiate delegate to reference uppercaseString function
let convertMeth = ConvertMethod uppercaseString
let name = "Dakota"

// Use delegate instance to call uppercaseString function
printfn $"{convertMeth.Invoke name}"
' 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> 명시적으로 새 대리자를 정의 하 고 명명된 된 메서드를 할당 하는 대신 대리자입니다.

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

string UppercaseString(string inputString)
{
   return inputString.ToUpper();
}

// This code example produces the following output:
//
//    DAKOTA
open System

let uppercaseString (inputString: string) =
    inputString.ToUpper()

// Instantiate delegate to reference uppercaseString function
let convertMethod = Func<string, string> uppercaseString
let name = "Dakota"

// Use delegate instance to call uppercaseString function
printfn $"{convertMethod.Invoke name}"

// This code example produces the following output:
//    DAKOTA
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

사용할 수도 있습니다는 Func<T,TResult> 다음 예제와 같이 C#에서는 무명 메서드로 위임 합니다. (소개 무명 메서드를 참조 하세요 무명 메서드.)

 Func<string, string> convert = delegate(string s)
    { return s.ToUpper();};

 string name = "Dakota";
 Console.WriteLine(convert(name));

// This code example produces the following output:
//
//    DAKOTA

람다 식을 할당할 수도 있습니다는 Func<T,TResult> 다음 예제와 같이 대리자입니다. 람다 식에 대 한 소개는 람다 식 (VB), 람다 식 (c #)람다 식 (F #)을 참조 하세요.

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

string name = "Dakota";
Console.WriteLine(convert(name));

// This code example produces the following output:
//
//    DAKOTA
open System

let convert = Func<string, string>(fun s -> s.ToUpper())

let name = "Dakota"
printfn $"{convert.Invoke name}"

// This code example produces the following output:
//    DAKOTA
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

람다 식의 기본 형식이 제네릭 중 하나인 Func 대리자입니다. 이 대리자를 명시적으로 할당 하지 않고 람다 식을 매개 변수로 전달할 수 있습니다. 특히 때문에 형식의 여러 메서드를 System.Linq 네임 스페이스 Func<T,TResult> 매개 변수를 하면 이러한 메서드는 람다 식을 전달할 수 명시적으로 인스턴스화하지 않고도 Func<T,TResult> 위임 합니다.

확장 메서드

GetMethodInfo(Delegate)

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

적용 대상

추가 정보