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

이 대리자로 캡슐화되는 메서드의 첫 번째 매개 변수 형식입니다.

이 형식 매개 변수는 반공변(Contravariant)입니다. 즉, 지정한 형식이나 더 적게 파생된 모든 형식을 사용할 수 있습니다. 공변성(Covariance) 및 반공변성(Contravariance)에 대한 자세한 내용은 제네릭의 공변성(Covariance) 및 반공변성(Contravariance)을 참조하세요.
T2

이 대리자로 캡슐화되는 메서드의 두 번째 매개 변수 형식입니다.

이 형식 매개 변수는 반공변(Contravariant)입니다. 즉, 지정한 형식이나 더 적게 파생된 모든 형식을 사용할 수 있습니다. 공변성(Covariance) 및 반공변성(Contravariance)에 대한 자세한 내용은 제네릭의 공변성(Covariance) 및 반공변성(Contravariance)을 참조하세요.

매개 변수

arg1
T1

이 대리자로 캡슐화되는 메서드의 첫 번째 매개 변수입니다.

arg2
T2

이 대리자로 캡슐화되는 메서드의 두 번째 매개 변수입니다.

설명

사용자 지정 대리자를 Action<T1,T2> 명시적으로 선언하지 않고 대리자를 사용하여 메서드를 매개 변수로 전달할 수 있습니다. 캡슐화 된 메서드에이 대리자에 의해 정의 되는 메서드 시그니처와 일치 해야 합니다. 즉, 캡슐화된 메서드에는 값으로 전달되는 두 개의 매개 변수가 있어야 하며 값을 반환해서는 안 됩니다. (C#에서는 메서드 반환 해야 void합니다. F#에서 메서드 또는 함수는 단위를 반환해야 합니다. Visual Basic의 경우에서 정의 되어야 합니다는 Sub...End Sub 구문입니다. 또한 수 무시 되는 값을 반환 하는 메서드입니다.) 일반적으로 이러한 메서드는 작업을 수행 하는 합니다.

참고

두 개의 매개 변수가 있고 값을 반환하는 메서드를 참조하려면 대신 제네릭 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#에서는 무명 메서드로 위임 합니다. (소개 무명 메서드를 참조 하세요 무명 메서드.)

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

람다 식을 할당할 수도 있습니다는 Action<T1,T2> 다음 예제와 같이 인스턴스를 위임 합니다. (람다 식에 대한 소개는 람다 식(C#) 또는 람다 식(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)

지정된 대리자가 나타내는 메서드를 나타내는 개체를 가져옵니다.

적용 대상

추가 정보