Func<T1,T2,T3,T4,TResult> Делегат
Определение
Важно!
Некоторые сведения относятся к предварительной версии продукта, в которую до выпуска могут быть внесены существенные изменения. Майкрософт не предоставляет никаких гарантий, явных или подразумеваемых, относительно приведенных здесь сведений.
Инкапсулирует метод с четырьмя параметрами и возвращает значение типа, указанного параметром TResult .
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
Параметры типа
- T1
Тип первого параметра метода, который инкапсулирует этот делегат.
Это контравариантный параметр типа. Это означает, что вы можете использовать любой из указанных типов или любой тип, являющийся менее производным. Дополнительные сведения о ковариантности и контрвариантности см. в статье Ковариантность и контрвариантность в универсальных шаблонах.- T2
Тип второго параметра метода, который инкапсулирует этот делегат.
Это контравариантный параметр типа. Это означает, что вы можете использовать любой из указанных типов или любой тип, являющийся менее производным. Дополнительные сведения о ковариантности и контрвариантности см. в статье Ковариантность и контрвариантность в универсальных шаблонах.- T3
Тип третьего параметра метода, инкапсулируемого этим делегатом.
Это контравариантный параметр типа. Это означает, что вы можете использовать любой из указанных типов или любой тип, являющийся менее производным. Дополнительные сведения о ковариантности и контрвариантности см. в статье Ковариантность и контрвариантность в универсальных шаблонах.- T4
Тип четвертого параметра метода, который инкапсулирует этот делегат.
Это контравариантный параметр типа. Это означает, что вы можете использовать любой из указанных типов или любой тип, являющийся менее производным. Дополнительные сведения о ковариантности и контрвариантности см. в статье Ковариантность и контрвариантность в универсальных шаблонах.- TResult
Тип возвращаемого значения метода, инкапсулируемого этим делегатом.
Это ковариантный параметр типа. Это означает, что вы можете использовать любой из указанных типов или любой тип, являющийся более производным. Дополнительные сведения о ковариантности и контрвариантности см. в статье Ковариантность и контрвариантность в универсальных шаблонах.Параметры
- arg1
- T1
Первый параметр метода, который инкапсулирует этот делегат.
- arg2
- T2
Второй параметр метода, который инкапсулирует этот делегат.
- arg3
- T3
Третий параметр метода, который инкапсулирует этот делегат.
- arg4
- T4
Четвертый параметр метода, который инкапсулирует этот делегат.
Возвращаемое значение
Возвращаемое значение метода, который инкапсулирует этот делегат.
Примеры
В следующем примере показано, как объявить и использовать 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
Комментарии
Этот делегат можно использовать для представления метода, который можно передать в качестве параметра без явного объявления пользовательского делегата. Инкапсулированный метод должен соответствовать сигнатуре метода, определенной этим делегатом. Это означает, что инкапсулированный метод должен иметь четыре параметра, каждый из которых передается в него по значению, и что он должен возвращать значение.
Note
Чтобы ссылаться на метод, имеющий четыре параметра и возвращающий void (unit в F#) (или в Visual Basic, который объявляется как Sub, а не как Function), используйте вместо этого универсальный делегат Action<T1,T2,T3,T4>.
При использовании делегата Func<T1,T2,T3,T4,TResult> не нужно явно определять делегат, инкапсулирующий метод с четырьмя параметрами. Например, следующий код явно объявляет универсальный делегат с именем Searcher и назначает ссылку на IndexOf метод своему экземпляру делегата.
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
В следующем примере этот код упрощается путем создания экземпляра Func<T1,T2,T3,T4,TResult> делегата вместо явного определения нового делегата и назначения именованного метода.
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
Делегат можно использовать с анонимными методами Func<T1,T2,T3,T4,TResult> в C#, как показано в следующем примере. (Введение в анонимные методы см. в разделе "Анонимные методы".)
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);
}
}
Можно также назначить лямбда-выражение Func<T1,T2,TResult> делегату, как показано в следующем примере. (Введение в лямбда-выражения см. в лямбда-выражениях (VB), лямбда-выражениях(C#) и лямбда-выражениях (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
Базовый тип лямбда-выражения является одним из универсальных Func делегатов. Это позволяет передать лямбда-выражение в качестве параметра без явного назначения его делегату. В частности, поскольку многие методы типов в System.Linq пространстве имен имеют Func параметры, эти методы можно передать лямбда-выражение без явного создания экземпляра делегата Func .
Методы расширения
| Имя | Описание |
|---|---|
| GetMethodInfo(Delegate) |
Возвращает объект, представляющий метод, представленный указанным делегатом. |