Func<T1,T2,T3,T4,TResult> Delegar

Definição

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

generic <typename T1, typename T2, typename T3, typename T4, typename TResult>
public delegate TResult Func(T1 arg1, T2 arg2, T3 arg3, T4 arg4);
public delegate TResult Func<in T1,in T2,in T3,in T4,out TResult>(T1 arg1, T2 arg2, T3 arg3, T4 arg4);
public delegate TResult Func<in T1,in T2,in T3,in T4,out TResult>(T1 arg1, T2 arg2, T3 arg3, T4 arg4) where T1 : allows ref struct where T2 : allows ref struct where T3 : allows ref struct where T4 : allows ref struct where TResult : allows ref struct;
public delegate TResult Func<T1,T2,T3,T4,TResult>(T1 arg1, T2 arg2, T3 arg3, T4 arg4);
type Func<'T1, 'T2, 'T3, 'T4, 'Result> = delegate of 'T1 * 'T2 * 'T3 * 'T4 -> 'Result
Public Delegate Function Func(Of In T1, In T2, In T3, In T4, Out TResult)(arg1 As T1, arg2 As T2, arg3 As T3, arg4 As T4) As TResult 
Public Delegate Function Func(Of T1, T2, T3, T4, TResult)(arg1 As T1, arg2 As T2, arg3 As T3, arg4 As T4) As TResult 

Parâmetros de Tipo Genérico

T1

O tipo do primeiro 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.
T2

O tipo do segundo 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.
T3

O tipo do terceiro 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.
T4

O tipo do quarto 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

arg1
T1

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

arg2
T2

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

arg3
T3

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

arg4
T4

O quarto 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<T1,T2,TResult> delegado. Este exemplo declara uma Func<T1,T2,TResult> variável e atribui-lhe uma expressão lambda que toma um String valor e um Int32 valor como parâmetros. A expressão lambda retorna true se o comprimento do String parâmetro for igual ao valor do Int32 parâmetro. O delegado que encapsula este método é posteriormente usado numa consulta para filtrar cadeias num array de cadeias.

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

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 quatro parâmetros, cada um dos quais lhe é passado por valor, e que deve devolver um valor.

Note

Para referenciar um método que tem quatro parâmetros e devolve void (unit em F#) (ou em Visual Basic, que é declarado como um Sub em vez de Function), use o delegado genérico Action<T1,T2,T3,T4> em vez disso.

Quando usa o Func<T1,T2,T3,T4,TResult> delegado, não precisa de definir explicitamente um delegado que encapsule um método com quatro parâmetros. Por exemplo, o código seguinte declara explicitamente um delegado genérico nomeado Searcher e atribui uma referência ao IndexOf método à sua instância delegada.

using System;

delegate int Searcher(string searchString, int start, int count,
                         StringComparison type);

public class DelegateExample
{
   public static void Main()
   {
      string title = "The House of the Seven Gables";
      int position = 0;
      Searcher finder = title.IndexOf;
      do
      {
         int characters = title.Length - position;
         position = finder("the", position, characters,
                         StringComparison.InvariantCultureIgnoreCase);
         if (position >= 0)
         {
            position++;
            Console.WriteLine("'The' found at position {0} in {1}.",
                              position, title);
         }
      } while (position > 0);
   }
}
open System

type Searcher = delegate of (string * int * int * StringComparison) -> int

let title = "The House of the Seven Gables"
let finder = Searcher title.IndexOf
let mutable position = 0

while position > -1 do
    let characters = title.Length - position
    position <- 
        finder.Invoke("the", position, characters, StringComparison.InvariantCultureIgnoreCase)
    if position >= 0 then
        position <- position + 1
        printfn $"'The' found at position {position} in {title}."
Delegate Function Searcher(searchString As String, _
                           start As Integer,  _
                           count As Integer, _
                           type As StringComparison) As Integer

Module DelegateExample
   Public Sub Main()
      Dim title As String = "The House of the Seven Gables"
      Dim position As Integer = 0
      Dim finder As Searcher = AddressOf title.IndexOf
      Do
         Dim characters As Integer = title.Length - position
         position = finder("the", position, characters, _
                         StringComparison.InvariantCultureIgnoreCase) 
         If position >= 0 Then
            position += 1
            Console.WriteLine("'The' found at position {0} in {1}.", _
                              position, title)
         End If   
      Loop While position > 0   
   End Sub
End Module

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

using System;

public class DelegateExample
{
   public static void Main()
   {
      string title = "The House of the Seven Gables";
      int position = 0;
      Func<string, int, int, StringComparison, int> finder = title.IndexOf;
      do
      {
         int characters = title.Length - position;
         position = finder("the", position, characters,
                         StringComparison.InvariantCultureIgnoreCase);
         if (position >= 0)
         {
            position++;
            Console.WriteLine("'The' found at position {0} in {1}.",
                              position, title);
         }
      } while (position > 0);
   }
}
open System

let indexOf (s: string) s2 pos chars comparison =
    s.IndexOf(s2, pos, chars, comparison) 

let title = "The House of the Seven Gables"
let finder = Func<string, int, int, StringComparison, int>(indexOf title)
let mutable position = 0

while position > -1 do
    let characters = title.Length - position
    position <- 
        finder.Invoke("the", position, characters, StringComparison.InvariantCultureIgnoreCase)
    if position >= 0 then
        position <- position + 1
        printfn $"'The' found at position {position} in {title}."
Module DelegateExample
   Public Sub Main()
      Dim title As String = "The House of the Seven Gables"
      Dim position As Integer = 0
      Dim finder As Func(Of String, Integer, Integer, StringComparison, Integer) _
                    = AddressOf title.IndexOf
      Do
         Dim characters As Integer = title.Length - position
         position = finder("the", position, characters, _
                         StringComparison.InvariantCultureIgnoreCase) 
         If position >= 0 Then
            position += 1
            Console.WriteLine("'The' found at position {0} in {1}.", _
                              position, title)
         End If   
      Loop While position > 0   
   End Sub
End Module

Pode usar o Func<T1,T2,T3,T4,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.)

using System;

public class DelegateExample
{
   public static void Main()
   {
      string title = "The House of the Seven Gables";
      int position = 0;
      Func<string, int, int, StringComparison, int> finder =
           delegate(string s, int pos, int chars, StringComparison type)
           { return title.IndexOf(s, pos, chars, type); };
      do
      {
         int characters = title.Length - position;
         position = finder("the", position, characters,
                         StringComparison.InvariantCultureIgnoreCase);
         if (position >= 0)
         {
            position++;
            Console.WriteLine("'The' found at position {0} in {1}.",
                              position, title);
         }
      } while (position > 0);
   }
}

Também pode atribuir uma expressão lambda a um Func<T1,T2,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#).)

using System;

public class DelegateExample
{
   public static void Main()
   {
      string title = "The House of the Seven Gables";
      int position = 0;
      Func<string, int, int, StringComparison, int> finder =
           (s, pos, chars, type) => title.IndexOf(s, pos, chars, type);
      do
      {
         int characters = title.Length - position;
         position = finder("the", position, characters,
                         StringComparison.InvariantCultureIgnoreCase);
         if (position >= 0)
         {
            position++;
            Console.WriteLine("'The' found at position {0} in {1}.",
                              position, title);
         }
      } while (position > 0);
   }
}
open System

let title = "The House of the Seven Gables"

let finder =
    Func<string, int, int, StringComparison, int>(fun s pos chars typ -> title.IndexOf(s, pos, chars, typ))

let mutable position = 0

while position > -1 do
    let characters = title.Length - position
    position <- finder.Invoke("the", position, characters, StringComparison.InvariantCultureIgnoreCase)

    if position >= 0 then
        position <- position + 1
        printfn $"'The' found at position {position} in {title}."
Module DelegateExample
   Public Sub Main()
      Dim title As String = "The House of the Seven Gables"
      Dim position As Integer = 0
      Dim finder As Func(Of String, Integer, Integer, StringComparison, Integer) _
                    = Function(s, pos, chars, type) _
                    title.IndexOf(s, pos, chars, type)
      Do
         Dim characters As Integer = title.Length - position
         position = finder("the", position, characters, _
                         StringComparison.InvariantCultureIgnoreCase) 
         If position >= 0 Then
            position += 1
            Console.WriteLine("'The' found at position {0} in {1}.", _
                              position, title)
         End If   
      Loop While position > 0   
   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 parâmetros, pode passar a esses métodos uma expressão lambda sem instanciar explicitamente um Func 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