Action<T1,T2> 委托
定义
重要
一些信息与预发行产品相关,相应产品在发行之前可能会进行重大修改。 对于此处提供的信息,Microsoft 不作任何明示或暗示的担保。
封装一个方法,该方法具有两个参数且不返回值。
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 -> unitPublic 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)类型参数
参数
- 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) | 获取指示指定委托表示的方法的对象。 |