Action<T1,T2> Delegasikan

Definisi

Merangkum metode yang memiliki dua parameter dan tidak mengembalikan nilai.

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<in T1,in T2>(T1 arg1, T2 arg2) where T1 : allows ref struct where T2 : allows ref struct;
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)

Jenis parameter

T1

Jenis parameter pertama metode yang dienkapsulasi delegasi ini.

Parameter jenis ini bersifat kontravarian. Artinya, Anda bisa menggunakan jenis yang Anda tentukan atau jenis apa pun yang tidak banyak diturunkan. Untuk informasi lebih lanjut tentang kovariansi dan kontravariansi, lihat Kovariansi dan Kontravariansi dalam Generik.
T2

Jenis parameter kedua metode yang dienkapsulasi delegasi ini.

Parameter jenis ini bersifat kontravarian. Artinya, Anda bisa menggunakan jenis yang Anda tentukan atau jenis apa pun yang tidak banyak diturunkan. Untuk informasi lebih lanjut tentang kovariansi dan kontravariansi, lihat Kovariansi dan Kontravariansi dalam Generik.

Parameter

arg1
T1

Parameter pertama metode yang dienkapsulasi delegasi ini.

arg2
T2

Parameter kedua metode yang dienkapsulasi delegasi ini.

Keterangan

Anda dapat menggunakan Action<T1,T2> delegasi untuk meneruskan metode sebagai parameter tanpa secara eksplisit mendeklarasikan delegasi kustom. Metode yang dienkapsulasi harus sesuai dengan tanda tangan metode yang ditentukan oleh delegasi ini. Ini berarti bahwa metode yang dienkapsulasi harus memiliki dua parameter yang keduanya diteruskan ke dalamnya berdasarkan nilai, dan tidak boleh mengembalikan nilai. (Dalam C#, metode harus mengembalikan void. Di F#, metode atau fungsi harus mengembalikan unit. Dalam Visual Basic, itu harus didefinisikan oleh Sub... End Sub konstruksi. Ini juga bisa menjadi metode yang mengembalikan nilai yang diabaikan.) Biasanya, metode seperti itu digunakan untuk melakukan operasi.

Note

Untuk mereferensikan metode yang memiliki dua parameter dan mengembalikan nilai, gunakan delegasi generik Func<T1,T2,TResult> sebagai gantinya.

Saat Anda menggunakan Action<T1,T2> delegasi, Anda tidak perlu secara eksplisit menentukan delegasi yang merangkum metode dengan dua parameter. Misalnya, kode berikut secara eksplisit menyatakan delegasi bernama ConcatStrings. Kemudian menetapkan referensi ke salah satu dari dua metode ke instans delegasinya. Satu metode menulis dua string ke konsol; yang kedua menulis dua string ke file.

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

Contoh berikut menyederhanakan kode ini dengan membuat instans delegasi Action<T1,T2> alih-alih secara eksplisit menentukan delegasi baru dan menetapkan metode bernama untuknya.

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

Anda juga dapat menggunakan Action<T1,T2> delegasi dengan metode anonim di C#, seperti yang diilustrasikan contoh berikut. (Untuk pengenalan metode anonim, lihat Metode Anonim.)

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

Anda juga dapat menetapkan ekspresi lambda ke Action<T1,T2> instans delegasi, seperti yang diilustrasikan contoh berikut. (Untuk pengenalan ekspresi lambda, lihat Ekspresi Lambda (C#), atau Ekspresi 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

Metode Ekstensi

Nama Deskripsi
GetMethodInfo(Delegate)

Mendapatkan objek yang mewakili metode yang diwakili oleh delegasi yang ditentukan.

Berlaku untuk

Lihat juga