Func<TResult> Delegar
Definição
Importante
Algumas informações dizem respeito a um produto pré-lançado que pode ser substancialmente modificado antes de ser lançado. A Microsoft não faz garantias, de forma expressa ou implícita, em relação à informação aqui apresentada.
Encapsula um método que não tem parâmetros e devolve um valor do tipo especificado pelo TResult parâmetro.
generic <typename TResult>
public delegate TResult Func();
public delegate TResult Func<out TResult>();
public delegate TResult Func<out TResult>() where TResult : allows ref struct;
public delegate TResult Func<TResult>();
type Func<'Result> = delegate of unit -> 'Result
Public Delegate Function Func(Of Out TResult)() As TResult
Public Delegate Function Func(Of TResult)() As TResult
Parâmetros de Tipo 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.Devolver Valor
O valor de retorno do método que este delegado encapsula.
Exemplos
O exemplo seguinte demonstra como usar um delegado que não utiliza parâmetros. Este código cria uma classe genérica chamada LazyValue que tem um corpo de tipo Func<TResult>. Este campo delegado pode armazenar uma referência a qualquer função que devolva um valor do tipo correspondente ao parâmetro de tipo do LazyValue objeto. O LazyValue tipo também tem uma Value propriedade que executa a função (caso ainda não tenha sido executada) e devolve o valor resultante.
O exemplo cria dois métodos e instancia dois LazyValue objetos com expressões lambda que chamam estes métodos. As expressões lambda não aceitam parâmetros porque só precisam de chamar um método. Como a saída mostra, os dois métodos só são executados quando o valor de cada LazyValue objeto é recuperado.
using System;
static class Func1
{
public static void Main()
{
// Note that each lambda expression has no parameters.
LazyValue<int> lazyOne = new LazyValue<int>(() => ExpensiveOne());
LazyValue<long> lazyTwo = new LazyValue<long>(() => ExpensiveTwo("apple"));
Console.WriteLine("LazyValue objects have been created.");
// Get the values of the LazyValue objects.
Console.WriteLine(lazyOne.Value);
Console.WriteLine(lazyTwo.Value);
}
static int ExpensiveOne()
{
Console.WriteLine("\nExpensiveOne() is executing.");
return 1;
}
static long ExpensiveTwo(string input)
{
Console.WriteLine("\nExpensiveTwo() is executing.");
return (long)input.Length;
}
}
class LazyValue<T> where T : struct
{
private Nullable<T> val;
private Func<T> getValue;
// Constructor.
public LazyValue(Func<T> func)
{
val = null;
getValue = func;
}
public T Value
{
get
{
if (val == null)
// Execute the delegate.
val = getValue();
return (T)val;
}
}
}
/* The example produces the following output:
LazyValue objects have been created.
ExpensiveOne() is executing.
1
ExpensiveTwo() is executing.
5
*/
open System
type LazyValue<'T>(func: Func<'T>) =
let mutable value = ValueNone
member _.Value =
match value with
| ValueSome v -> v
| ValueNone ->
// Execute the delegate.
let v = func.Invoke()
value <- ValueSome v
v
let expensiveOne () =
printfn "\nExpensiveOne() is executing."
1
let expensiveTwo (input: string) =
printfn "\nExpensiveTwo() is executing."
int64 input.Length
// Note that each lambda expression has no parameters.
let lazyOne = LazyValue(fun () -> expensiveOne ())
let lazyTwo = LazyValue(fun () -> expensiveTwo "apple")
printfn "LazyValue objects have been created."
// Get the values of the LazyValue objects.
printfn $"{lazyOne.Value}"
printfn $"{lazyTwo.Value}"
// The example produces the following output:
// LazyValue objects have been created.
//
// ExpensiveOne() is executing.
// 1
//
// ExpensiveTwo() is executing.
// 5
Public Module Func
Public Sub Main()
' Note that each lambda expression has no parameters.
Dim lazyOne As New LazyValue(Of Integer)(Function() ExpensiveOne())
Dim lazyTwo As New LazyValue(Of Long)(Function() ExpensiveTwo("apple"))
Console.WriteLine("LazyValue objects have been created.")
' Get the values of the LazyValue objects.
Console.WriteLine(lazyOne.Value)
Console.WriteLine(lazyTwo.Value)
End Sub
Public Function ExpensiveOne() As Integer
Console.WriteLine()
Console.WriteLine("ExpensiveOne() is executing.")
Return 1
End Function
Public Function ExpensiveTwo(input As String) As Long
Console.WriteLine()
Console.WriteLine("ExpensiveTwo() is executing.")
Return input.Length
End Function
End Module
Public Class LazyValue(Of T As Structure)
Private val As Nullable(Of T)
Private getValue As Func(Of T)
' Constructor.
Public Sub New(func As Func(Of T))
Me.val = Nothing
Me.getValue = func
End Sub
Public ReadOnly Property Value() As T
Get
If Me.val Is Nothing Then
' Execute the delegate.
Me.val = Me.getValue()
End If
Return CType(val, T)
End Get
End Property
End Class
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 não deve ter parâmetros e deve devolver um valor.
Note
Para referenciar um método que não tem parâmetros e devolve void (unit, em F#) (ou em Visual Basic, que é declarado como um Sub em vez de Function), use o delegado Action em vez disso.
Quando usa o Func<TResult> delegado, não precisa de definir explicitamente um delegado que encapsule um método sem parâmetros. Por exemplo, o código seguinte declara explicitamente um delegado nomeado WriteMethod e atribui uma referência ao OutputTarget.SendToFile método de instância à sua instância delegada.
using System;
using System.IO;
delegate bool WriteMethod();
public class TestDelegate
{
public static void Main()
{
OutputTarget output = new OutputTarget();
WriteMethod methodCall = output.SendToFile;
if (methodCall())
Console.WriteLine("Success!");
else
Console.WriteLine("File write operation failed.");
}
}
public class OutputTarget
{
public bool SendToFile()
{
try
{
string fn = Path.GetTempFileName();
StreamWriter sw = new StreamWriter(fn);
sw.WriteLine("Hello, World!");
sw.Close();
return true;
}
catch
{
return false;
}
}
}
open System.IO
type WriteMethod = delegate of unit -> bool
type OutputTarget() =
member _.SendToFile() =
try
let fn = Path.GetTempFileName()
use sw = new StreamWriter(fn)
sw.WriteLine "Hello, World!"
true
with _ ->
false
let output = new OutputTarget()
let methodCall = WriteMethod output.SendToFile
if methodCall.Invoke() then
printfn "Success!"
else
printfn "File write operation failed."
Imports System.IO
Delegate Function WriteMethod As Boolean
Module TestDelegate
Public Sub Main()
Dim output As New OutputTarget()
Dim methodCall As WriteMethod = AddressOf output.SendToFile
If methodCall() Then
Console.WriteLine("Success!")
Else
Console.WriteLine("File write operation failed.")
End If
End Sub
End Module
Public Class OutputTarget
Public Function SendToFile() As Boolean
Try
Dim fn As String = Path.GetTempFileName
Dim sw As StreamWriter = New StreamWriter(fn)
sw.WriteLine("Hello, World!")
sw.Close
Return True
Catch
Return False
End Try
End Function
End Class
O exemplo seguinte simplifica este código ao instanciar o Func<TResult> delegado em vez de definir explicitamente um novo delegado e atribuir-lhe um método nomeado.
using System;
using System.IO;
public class TestDelegate
{
public static void Main()
{
OutputTarget output = new OutputTarget();
Func<bool> methodCall = output.SendToFile;
if (methodCall())
Console.WriteLine("Success!");
else
Console.WriteLine("File write operation failed.");
}
}
public class OutputTarget
{
public bool SendToFile()
{
try
{
string fn = Path.GetTempFileName();
StreamWriter sw = new StreamWriter(fn);
sw.WriteLine("Hello, World!");
sw.Close();
return true;
}
catch
{
return false;
}
}
}
open System
open System.IO
type OutputTarget() =
member _.SendToFile() =
try
let fn = Path.GetTempFileName()
use sw = new StreamWriter(fn)
sw.WriteLine "Hello, World!"
true
with _ ->
false
let output = OutputTarget()
let methodCall = Func<bool> output.SendToFile
if methodCall.Invoke() then
printfn "Success!"
else
printfn "File write operation failed."
Imports System.IO
Module TestDelegate
Public Sub Main()
Dim output As New OutputTarget()
Dim methodCall As Func(Of Boolean) = AddressOf output.SendToFile
If methodCall() Then
Console.WriteLine("Success!")
Else
Console.WriteLine("File write operation failed.")
End If
End Sub
End Module
Public Class OutputTarget
Public Function SendToFile() As Boolean
Try
Dim fn As String = Path.GetTempFileName
Dim sw As StreamWriter = New StreamWriter(fn)
sw.WriteLine("Hello, World!")
sw.Close
Return True
Catch
Return False
End Try
End Function
End Class
Pode usar o Func<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;
using System.IO;
public class Anonymous
{
public static void Main()
{
OutputTarget output = new OutputTarget();
Func<bool> methodCall = delegate() { return output.SendToFile(); };
if (methodCall())
Console.WriteLine("Success!");
else
Console.WriteLine("File write operation failed.");
}
}
public class OutputTarget
{
public bool SendToFile()
{
try
{
string fn = Path.GetTempFileName();
StreamWriter sw = new StreamWriter(fn);
sw.WriteLine("Hello, World!");
sw.Close();
return true;
}
catch
{
return false;
}
}
}
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#).)
using System;
using System.IO;
public class Anonymous
{
public static void Main()
{
OutputTarget output = new OutputTarget();
Func<bool> methodCall = () => output.SendToFile();
if (methodCall())
Console.WriteLine("Success!");
else
Console.WriteLine("File write operation failed.");
}
}
public class OutputTarget
{
public bool SendToFile()
{
try
{
string fn = Path.GetTempFileName();
StreamWriter sw = new StreamWriter(fn);
sw.WriteLine("Hello, World!");
sw.Close();
return true;
}
catch
{
return false;
}
}
}
open System
open System.IO
type OutputTarget() =
member _.SendToFile() =
try
let fn = Path.GetTempFileName()
use sw = new StreamWriter(fn)
sw.WriteLine "Hello, World!"
true
with _ ->
false
let output = OutputTarget()
let methodCall = Func<bool>(fun () -> output.SendToFile())
if methodCall.Invoke() then
printfn "Success!"
else
printfn "File write operation failed."
Imports System.IO
Module TestDelegate
Public Sub Main()
Dim output As New OutputTarget()
Dim methodCall As Func(Of Boolean) = Function() output.SendToFile()
If methodCall() Then
Console.WriteLine("Success!")
Else
Console.WriteLine("File write operation failed.")
End If
End Sub
End Module
Public Class OutputTarget
Public Function SendToFile() As Boolean
Try
Dim fn As String = Path.GetTempFileName
Dim sw As StreamWriter = New StreamWriter(fn)
sw.WriteLine("Hello, World!")
sw.Close
Return True
Catch
Return False
End Try
End Function
End Class
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.
Se tiver um cálculo dispendioso que só quer executar se o resultado for realmente necessário, pode atribuir a função cara a um Func<TResult> delegado. A execução da função pode então ser adiada até que uma propriedade que acede ao valor seja usada numa expressão. O exemplo na secção seguinte demonstra como fazer isto.
Métodos da Extensão
| Name | Descrição |
|---|---|
| GetMethodInfo(Delegate) |
Obtém um objeto que representa o método representado pelo delegado especificado. |