Func<TResult> Func<TResult> Func<TResult> Func<TResult> Delegate

定義

パラメーターを受け取らずに、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>();
type Func<'Result> = delegate of unit -> 'Result
Public Delegate Function Func(Of Out 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.

継承
Func<TResult>Func<TResult>Func<TResult>Func<TResult>

次の例では、パラメーターをとらないデリゲートを使用する方法を示します。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>. このデリゲート フィールドの型パラメーターに対応する型の値を返す任意の関数への参照を格納できます、LazyValueオブジェクト。This 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.

この例は、2 つのメソッドを作成し、2 つのインスタンスを作成LazyValueをこれらのメソッドを呼び出すラムダ式を持つオブジェクト。The example creates two methods and instantiates two LazyValue objects with lambda expressions that call these methods. ラムダ式は、メソッドを呼び出すだけなのでパラメーターになりません。The lambda expressions do not take parameters because they just need to call a method. 出力を 2 つのメソッドが実行される場合にのみの各値LazyValueオブジェクトを取得します。As 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;
      }
   }
}

ラムダ式を割り当てることもできます、Func<T,TResult>デリゲート、次の例に示すようにします。You can also assign a lambda expression to a Func<T,TResult> delegate, as the following example illustrates. (ラムダ式の概要については、次を参照してくださいラムダ式ラムダ式。)。(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

ラムダ式の基になる型がジェネリックのいずれかのFuncデリゲート。The underlying type of a lambda expression is one of the generic Func delegates. これによりを明示的にデリゲートに割り当てることがなく、パラメーターとしてラムダ式を渡すことができます。This makes it possible to pass a lambda expression as a parameter without explicitly assigning it to a delegate. 具体的には、ため、型の多くのメソッド、System.Linq名前空間がFuncパラメーターを渡すことができますこれらのメソッド、ラムダ式に明示的にインスタンス化せず、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) GetMethodInfo(Delegate) GetMethodInfo(Delegate) GetMethodInfo(Delegate)

指定したデリゲートによって表されるメソッドを表すオブジェクトを取得します。Gets an object that represents the method represented by the specified delegate.

適用対象

こちらもご覧ください