Func<T,TResult> Delegar

Definição

Encapsula um método que tem um parâmetro e devolve um valor do tipo especificado pelo TResult parâmetro.

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 

Parâmetros de Tipo Genérico

T

O tipo do parâmetro do método que este delegado encapsula.

Este parâmetro de tipo é contravariante. Ou seja, pode utilizar o tipo que especificou ou qualquer tipo que seja menos derivado. Para obter mais informações sobre covariância e contravariância, veja Covariância e Contravariância em Genérico.
TResult

O tipo do valor de retorno do método que este delegado encapsula.

Este parâmetro de tipo é covariante. Ou seja, pode utilizar o tipo que especificou ou qualquer tipo que seja mais derivado. Para obter mais informações sobre covariância e contravariância, veja Covariância e Contravariância em Genérico.

Parâmetros

arg
T

O parâmetro do método que este delegado encapsula.

Devolver Valor

TResult

O valor de retorno do método que este delegado encapsula.

Exemplos

O exemplo seguinte demonstra como declarar e usar um Func<T,TResult> delegado. Este exemplo declara uma Func<T,TResult> variável e atribui-lhe uma expressão lambda que converte os caracteres de uma string em maiúsculas. O delegado que encapsula este método é posteriormente passado ao Enumerable.Select método para mudar as cordas de um array de cadeias para maiúsculas.

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

Observações

Pode usar este delegado para representar um método que pode ser passado como parâmetro sem declarar explicitamente um delegado personalizado. O método encapsulado deve corresponder à assinatura do método definida por este delegado. Isto significa que o método encapsulado deve ter um parâmetro que lhe é passado por valor, e que deve devolver um valor.

Note

Para referenciar um método que tem um parâmetro e devolve void (ou em Visual Basic, que é declarado como Sub em vez de Function), use o delegado genérico Action<T> em vez disso.

Quando usa o Func<T,TResult> delegado, não precisa de definir explicitamente um delegado que encapsule um método com um único parâmetro. Por exemplo, o código seguinte declara explicitamente um delegado nomeado ConvertMethod e atribui uma referência ao UppercaseString método à sua instância delegada.

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

O exemplo seguinte simplifica este código ao instanciar o Func<T,TResult> delegado em vez de definir explicitamente um novo delegado e atribuir-lhe um método nomeado.

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

Também pode usar o Func<T,TResult> delegado com métodos anónimos em C#, como o exemplo seguinte ilustra. (Para uma introdução aos métodos anónimos, veja Métodos Anónimos.)

 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

Também pode atribuir uma expressão lambda a um Func<T,TResult> delegado, como ilustra o exemplo seguinte. (Para uma introdução às expressões lambda, veja Expressões Lambda (VB),Expressões Lambda (C#) e Expressões Lambda (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

O tipo subjacente de uma expressão lambda é um dos delegados genéricos Func . Isto torna possível passar uma expressão lambda como parâmetro sem a atribuir explicitamente a um delegado. Em particular, porque muitos métodos de tipos no System.Linq namespace têm Func<T,TResult> parâmetros, pode passar a esses métodos uma expressão lambda sem instanciar explicitamente um Func<T,TResult> delegado.

Métodos da Extensão

Name Description
GetMethodInfo(Delegate)

Obtém um objeto que representa o método representado pelo delegado especificado.

Aplica-se a

Ver também