Func<TResult> 代理人

定義

封裝沒有參數並傳回 TResult 參數所指定之類型值的方法。Encapsulates a method that has no parameters and returns a value of the type specified by the TResult parameter.

generic <typename TResult>
public delegate TResult Func();
public delegate TResult Func<out TResult>();
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 

類型參數

TResult

這個委派所封裝之方法的傳回值之類型。The type of the return value of the method that this delegate encapsulates.

這是共變數的型別參數。 也就是說,您可以使用您指定的類型,或衍生程度較高的任何類型。 如需共變數與反變數的詳細資訊,請參閱泛型中的共變數與反變數

傳回值

TResult

這個委派所封裝之方法的傳回值。The return value of the method that this delegate encapsulates.

範例

下列範例示範如何使用不接受任何參數的委派。The following example demonstrates how to use a delegate that takes no parameters. 此程式碼會建立名為 LazyValue 的泛型類別,其具有類型的欄位 Func<TResult>This code creates a generic class named LazyValue that has a field of type Func<TResult>. 這個委派欄位可以儲存任何函式的參考,該函式會傳回對應至物件之型別參數的型別值 LazyValueThis delegate field can store a reference to any function that returns a value of the type that corresponds to the type parameter of the LazyValue object. LazyValue 類型也具有執行函式 Value (的屬性(如果尚未執行)) 並傳回產生的值。The LazyValue type also has a Value property that executes the function (if it has not already been executed) and returns the resulting value.

此範例會建立兩個方法,並 LazyValue 使用呼叫這些方法的 lambda 運算式來具現化兩個物件。The example creates two methods and instantiates two LazyValue objects with lambda expressions that call these methods. Lambda 運算式不會採用參數,因為它們只需要呼叫方法。The lambda expressions do not take parameters because they just need to call a method. 如輸出所示,只有在抓取每個物件的值時,才會執行這兩個方法 LazyValueAs the output shows, the two methods are executed only when the value of each LazyValue object is retrieved.

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

備註

您可以使用這個委派來代表可以傳遞為參數的方法,而不需要明確宣告自訂委派。You can use this delegate to represent a method that can be passed as a parameter without explicitly declaring a custom delegate. 封裝的方法必須對應至這個委派所定義的方法簽章。The encapsulated method must correspond to the method signature that is defined by this delegate. 這表示封裝的方法必須沒有參數,而且必須傳回值。This means that the encapsulated method must have no parameters and must return a value.

注意

若要參考沒有參數的方法,並傳回 void (或 Visual Basic 中宣告為,而不是 Sub 做為) 的方法 Function ,請改為使用 Action 委派。To reference a method that has no parameters and returns void (or in Visual Basic, that is declared as a Sub rather than as a Function), use the Action delegate instead.

當您使用 Func<TResult> 委派時,不需要明確定義封裝無參數方法的委派。When you use the Func<TResult> delegate, you do not have to explicitly define a delegate that encapsulates a parameterless method. 例如,下列程式碼會明確宣告名為的委派, WriteMethod 並將實例方法的參考指派 OutputTarget.SendToFile 給它的委派實例。For example, the following code explicitly declares a delegate named WriteMethod and assigns a reference to the OutputTarget.SendToFile instance method to its delegate instance.

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;
      }
   }
}
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

下列範例會藉由具現化委派來簡化此程式碼 Func<TResult> ,而不是明確定義新的委派,並將命名方法指派給它。The following example simplifies this code by instantiating the Func<TResult> delegate instead of explicitly defining a new delegate and assigning a named method to it.

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;
      }
   }
}
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

您可以 Func<TResult> 在 c # 中搭配匿名方法使用委派,如下列範例所示。You can use the Func<TResult> delegate with anonymous methods in C#, as the following example illustrates. 如需匿名方法的簡介,請參閱 匿名方法 (。 ) (For an introduction to anonymous methods, see Anonymous Methods.)

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;
      }
   }
}

您也可以將 lambda 運算式指派給 Func<T,TResult> 委派,如下列範例所示。You can also assign a lambda expression to a Func<T,TResult> delegate, as the following example illustrates. (如需 lambda 運算式的簡介,請參閱 Lambda 運算式lambda 運算式。 ) (For an introduction to lambda expressions, see Lambda Expressions and Lambda Expressions.)

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;
      }
   }
}
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

Lambda 運算式的基礎類型是其中一個泛型 Func 委派。The underlying type of a lambda expression is one of the generic Func delegates. 如此一來,您就可以將 lambda 運算式當做參數傳遞,而不需要明確地將它指派給委派。This makes it possible to pass a lambda expression as a parameter without explicitly assigning it to a delegate. 尤其是,由於命名空間中的許多類型方法 System.Linq 都有 Func 參數,您可以將這些方法傳遞給 lambda 運算式,而不需要明確具現化 Func 委派。In particular, because many methods of types in the System.Linq namespace have Func parameters, you can pass these methods a lambda expression without explicitly instantiating a Func delegate.

如果您有想要在實際需要結果的情況下執行的昂貴計算,則可以將昂貴的函式指派給 Func<TResult> 委派。If you have an expensive computation that you want to execute only if the result is actually needed, you can assign the expensive function to a Func<TResult> delegate. 然後,在運算式中使用存取此值的屬性之前,可以順延強制函數。The execution of the function can then be delayed until a property that accesses the value is used in an expression. 下一節中的範例將示範如何進行這項操作。The example in the next section demonstrates how to do this.

擴充方法

GetMethodInfo(Delegate)

取得表示特定委派所代表之方法的物件。Gets an object that represents the method represented by the specified delegate.

適用於