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<in T,out TResult>(T arg) where T : allows ref struct where TResult : allows ref struct;
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

설명

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

메모

매개 변수가 하나 있고 void(또는 Visual Basic Function 대신 Sub 선언됨)을 반환하는 메서드를 참조하려면 제네릭 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

다음 예제와 같이 C#에서 익명 메서드와 함께 대리자를 사용할 Func<T,TResult> 수도 있습니다. (익명 메서드에 대한 소개는 익명 메서드를 참조하세요.)

 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.LinqFunc<T,TResult> 매개 변수가 있으므로 대리자를 명시적으로 인스턴스화하지 않고도 이러한 메서드를 람다 식으로 Func<T,TResult> 전달할 수 있습니다.

확장명 메서드

Name Description
GetMethodInfo(Delegate)

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

적용 대상

추가 정보