Action<T1,T2> 代理人

定義

封裝具有 2 個參數且沒有傳回值的方法。

generic <typename T1, typename T2>
public delegate void Action(T1 arg1, T2 arg2);
public delegate void Action<in T1,in T2>(T1 arg1, T2 arg2);
public delegate void Action<T1,T2>(T1 arg1, T2 arg2);
type Action<'T1, 'T2> = delegate of 'T1 * 'T2 -> unit
Public Delegate Sub Action(Of In T1, In T2)(arg1 As T1, arg2 As T2)
Public Delegate Sub Action(Of T1, T2)(arg1 As T1, arg2 As T2)

類型參數

T1

此委派封裝之方法的第一個參數類型。

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

此委派封裝之方法的第二個參數類型。

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

參數

arg1
T1

由這個委派所封裝之方法的第一個參數。

arg2
T2

此委派封裝之方法的第二個參數。

備註

您可以使用 Action<T1,T2> 委派將方法當做參數傳遞,而不需明確宣告自訂委派。 封裝的方法必須對應至這個委派所定義的方法簽章。 這表示封裝的方法必須有兩個參數,兩個參數都是以傳值方式傳遞給它,而且不能傳回值。 (在 C# 中,方法必須傳回 void 。 在 F# 中,方法或函式必須傳回單位。 在Visual Basic中,它必須由 ... 定義 Sub``End Sub construct: 它也可以是傳回忽略之值的方法。) 通常,這類方法會用來執行作業。

注意

若要參考具有兩個參數並傳回值的方法,請改用泛型 Func<T1,T2,TResult> 委派。

當您使用委派時 Action<T1,T2> ,不需要明確定義封裝具有兩個參數之方法的委派。 例如,下列程式碼會明確宣告名為 的 ConcatStrings 委派。 然後,它會將兩個方法的其中一個參考指派給其委派實例。 一種方法會將兩個字串寫入主控台;第二個會將兩個字串寫入檔案。

using System;
using System.IO;

delegate void ConcatStrings(string string1, string string2);

public class TestDelegate
{
   public static void Main()
   {
      string message1 = "The first line of a message.";
      string message2 = "The second line of a message.";
      ConcatStrings concat;

      if (Environment.GetCommandLineArgs().Length > 1)
         concat = WriteToFile;
      else
         concat = WriteToConsole;

      concat(message1, message2);
   }

   private static void WriteToConsole(string string1, string string2)
   {
      Console.WriteLine("{0}\n{1}", string1, string2);
   }

   private static void WriteToFile(string string1, string string2)
   {
      StreamWriter writer = null;
      try
      {
         writer = new StreamWriter(Environment.GetCommandLineArgs()[1], false);
         writer.WriteLine("{0}\n{1}", string1, string2);
      }
      catch
      {
         Console.WriteLine("File write operation failed...");
      }
      finally
      {
         if (writer != null) writer.Close();
      }
   }
}
open System
open System.IO

type ConcatStrings = delegate of string1: string * string1: string -> unit

let message1 = "The first line of a message"
let message2 = "The second line of a message"

let writeToConsole string1 string2 = 
    printfn $"{string1}\n{string2}"

let writeToFile string1 string2 =
    use writer = new StreamWriter(Environment.GetCommandLineArgs().[1], false)
    writer.WriteLine $"{string1}\n{string2}"

let concat =
    ConcatStrings(fun string1 string2 ->
        if Environment.GetCommandLineArgs().Length > 1 then
            writeToFile string1 string2
        else
            writeToConsole string1 string2
    )

concat.Invoke(message1, message2)
Imports System.IO

Delegate Sub ConcatStrings(string1 As String, string2 As String)

Module TestDelegate
   Public Sub Main()
      
      Dim message1 As String = "The first line of a message."
      Dim message2 As String = "The second line of a message."
      Dim concat As ConcatStrings
      
      If Environment.GetCommandLineArgs().Length > 1 Then
         concat = AddressOf WriteToFile
      Else
         concat = AddressOf WriteToConsole
      End If   
      concat(message1, message2)         
   End Sub
   
   Private Sub WriteToConsole(string1 As String, string2 As String)
      Console.WriteLine("{0}{1}{2}", string1, vbCrLf, string2)
   End Sub
   
   Private Sub WriteToFile(string1 As String, string2 As String)
      Dim writer As StreamWriter = Nothing  
      Try
         writer = New StreamWriter(Environment.GetCommandLineArgs(1), False)
         writer.WriteLine("{0}{1}{2}", string1, vbCrLf, string2)
      Catch
         Console.WriteLine("File write operation failed...")
      Finally
         If writer IsNot Nothing Then writer.Close
      End Try      
   End Sub
End Module

下列範例會具現化委派, Action<T1,T2> 而不是明確定義新的委派,並將具名方法指派給它,藉此簡化此程式碼。

using System;
using System.IO;

public class TestAction2
{
   public static void Main()
   {
      string message1 = "The first line of a message.";
      string message2 = "The second line of a message.";
      Action<string, string> concat;

      if (Environment.GetCommandLineArgs().Length > 1)
         concat = WriteToFile;
      else
         concat = WriteToConsole;

      concat(message1, message2);
   }

   private static void WriteToConsole(string string1, string string2)
   {
      Console.WriteLine("{0}\n{1}", string1, string2);
   }

   private static void WriteToFile(string string1, string string2)
   {
      StreamWriter writer = null;
      try
      {
         writer = new StreamWriter(Environment.GetCommandLineArgs()[1], false);
         writer.WriteLine("{0}\n{1}", string1, string2);
      }
      catch
      {
         Console.WriteLine("File write operation failed...");
      }
      finally
      {
         if (writer != null) writer.Close();
      }
   }
}
open System
open System.IO

let message1 = "The first line of a message"
let message2 = "The second line of a message"

let writeToConsole string1 string2 = 
    printfn $"{string1}\n{string2}"

let writeToFile string1 string2 =
    use writer = new StreamWriter(Environment.GetCommandLineArgs().[1], false)
    writer.WriteLine $"{string1}\n{string2}"

let concat =
    Action<string, string>(fun string1 string2 ->
        if Environment.GetCommandLineArgs().Length > 1 then
            writeToFile string1 string2
        else
            writeToConsole string1 string2
    )

concat.Invoke(message1, message2)
Imports System.IO

Module TestAction2
   Public Sub Main()
      
      Dim message1 As String = "The first line of a message."
      Dim message2 As String = "The second line of a message."
      Dim concat As Action(Of String, String)
      
      If Environment.GetCommandLineArgs().Length > 1 Then
         concat = AddressOf WriteToFile
      Else
         concat = AddressOf WriteToConsole
      End If   
      concat(message1, message2)         
   End Sub
   
   Private Sub WriteToConsole(string1 As String, string2 As String)
      Console.WriteLine("{0}{1}{2}", string1, vbCrLf, string2)
   End Sub
   
   Private Sub WriteToFile(string1 As String, string2 As String)
      Dim writer As StreamWriter = Nothing  
      Try
         writer = New StreamWriter(Environment.GetCommandLineArgs(1), False)
         writer.WriteLine("{0}{1}{2}", string1, vbCrLf, string2)
      Catch
         Console.WriteLine("File write operation failed...")
      Finally
         If writer IsNot Nothing Then writer.Close
      End Try      
   End Sub
End Module

您也可以在 Action<T1,T2> C# 中搭配匿名方法使用委派,如下列範例所示。 (如需匿名方法的簡介,請參閱 Anonymous Methods.)

using System;
using System.IO;

public class TestAnonymousMethod
{
   public static void Main()
   {
      string message1 = "The first line of a message.";
      string message2 = "The second line of a message.";
      Action<string, string> concat;

      if (Environment.GetCommandLineArgs().Length > 1)
         concat = delegate(string s1, string s2) { WriteToFile(s1, s2); };
      else
         concat = delegate(string s1, string s2) { WriteToConsole(s1, s2);} ;

      concat(message1, message2);
   }

   private static void WriteToConsole(string string1, string string2)
   {
      Console.WriteLine("{0}\n{1}", string1, string2);
   }

   private static void WriteToFile(string string1, string string2)
   {
      StreamWriter writer = null;
      try
      {
         writer = new StreamWriter(Environment.GetCommandLineArgs()[1], false);
         writer.WriteLine("{0}\n{1}", string1, string2);
      }
      catch
      {
         Console.WriteLine("File write operation failed...");
      }
      finally
      {
         if (writer != null) writer.Close();
      }
   }
}

您也可以將 Lambda 運算式指派給 Action<T1,T2> 委派實例,如下列範例所示。 (如需 Lambda 運算式的簡介,請參閱 Lambda 運算式 (C#) Lambda 運算式 (F#) .)

using System;
using System.IO;

public class TestLambdaExpression
{
   public static void Main()
   {
      string message1 = "The first line of a message.";
      string message2 = "The second line of a message.";
      Action<string, string> concat;

      if (Environment.GetCommandLineArgs().Length > 1)
         concat = (s1, s2) => WriteToFile(s1, s2);
      else
         concat = (s1, s2) => WriteToConsole(s1, s2);

      concat(message1, message2);
   }

   private static void WriteToConsole(string string1, string string2)
   {
      Console.WriteLine("{0}\n{1}", string1, string2);
   }

   private static void WriteToFile(string string1, string string2)
   {
      StreamWriter writer = null;
      try
      {
         writer = new StreamWriter(Environment.GetCommandLineArgs()[1], false);
         writer.WriteLine("{0}\n{1}", string1, string2);
      }
      catch
      {
         Console.WriteLine("File write operation failed...");
      }
      finally
      {
         if (writer != null) writer.Close();
      }
   }
}
open System
open System.IO

let message1 = "The first line of a message"
let message2 = "The second line of a message"

let writeToConsole string1 string2 = 
    printfn $"{string1}\n{string2}"

let writeToFile string1 string2 =
    use writer = new StreamWriter(Environment.GetCommandLineArgs().[1], false)
    writer.WriteLine $"{string1}\n{string2}"

let concat =
    Action<string,string>(
        if Environment.GetCommandLineArgs().Length > 1 then
            fun s1 s2 -> writeToFile s1 s2
        else
            fun s1 s2 -> writeToConsole s1 s2
    )

concat.Invoke(message1, message2)
Imports System.IO

Public Module TestLambdaExpression

   Public Sub Main()
      Dim message1 As String = "The first line of a message."
      Dim message2 As String = "The second line of a message."
      Dim concat As Action(Of String, String)
      
      If Environment.GetCommandLineArgs().Length > 1 Then
         concat = Sub(s1, s2) WriteToFile(s1, s2)
      Else
         concat = Sub(s1, s2) WriteToConsole(s1, s2)
      End If
         
      concat(message1, message2)
   End Sub
  
   Private Function WriteToConsole(string1 As String, string2 As String) As Integer
      Dim message As String = String.Format("{0}{1}{2}", string1, vbCrLf, string2)
      Console.WriteLine(message)
      Return message.Length
   End Function

   Private Function WriteToFile(string1 As String, string2 As String) As Integer
      Dim writer As StreamWriter = Nothing  
      Dim message As String = String.Format("{0}{1}{2}", string1, vbCrLf, string2)
      Dim charsWritten As Integer
      Try
         writer = New StreamWriter(Environment.GetCommandLineArgs()(1), False)
         writer.WriteLine(message)
      Catch
         Console.WriteLine("File write operation failed...")
      Finally
         If writer IsNot Nothing Then 
            writer.Close()
            charsWritten = message.Length
         Else
            charsWritten = 0
         End If
      End Try      
      Return charsWritten
   End Function
End Module

擴充方法

GetMethodInfo(Delegate)

取得表示特定委派所代表之方法的物件。

適用於

另請參閱