Action<T> 대리자

정의

매개 변수가 하나이고 값을 반환하지 않는 메서드를 캡슐화합니다.

generic <typename T>
public delegate void Action(T obj);
public delegate void Action<in T>(T obj);
public delegate void Action<T>(T obj);
type Action<'T> = delegate of 'T -> unit
Public Delegate Sub Action(Of In T)(obj As T)
Public Delegate Sub Action(Of T)(obj As T)

형식 매개 변수

T

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

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

매개 변수

obj
T

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

예제

다음 예제에서는 대리자를 사용하여 Action<T> 개체의 List<T> 내용을 인쇄하는 방법을 보여 줍니다. 이 예제 Print 에서는 이 메서드를 사용하여 목록의 내용을 콘솔에 표시합니다. 또한 C# 예제에서는 익명 메서드를 사용하여 콘텐츠를 콘솔에 표시하는 방법도 보여 줍니다. 이 예제에서는 변수를 Action<T> 명시적으로 선언하지 않습니다. 대신 단일 매개 변수를 사용하고 단일 매개 변수가 대리자인 메서드에 List<T>.ForEach 값을 반환하지 않는 메서드에 대한 참조를 Action<T> 전달합니다. 마찬가지로 C# 예제 Action<T> 에서는 익명 메서드의 서명이 메서드에서 예상 List<T>.ForEach 하는 대리자의 서명 Action<T> 과 일치하므로 대리자가 명시적으로 인스턴스화되지 않습니다.

List<string> names = new List<string>();
names.Add("Bruce");
names.Add("Alfred");
names.Add("Tim");
names.Add("Richard");

// Display the contents of the list using the Print method.
names.ForEach(Print);

// The following demonstrates the anonymous method feature of C#
// to display the contents of the list to the console.
names.ForEach(delegate(string name)
{
    Console.WriteLine(name);
});

void Print(string s)
{
    Console.WriteLine(s);
}

/* This code will produce output similar to the following:
* Bruce
* Alfred
* Tim
* Richard
* Bruce
* Alfred
* Tim
* Richard
*/
// F# provides a type alias for System.Collections.List<'T> as ResizeArray<'T>.
let names = ResizeArray<string>()
names.Add "Bruce"
names.Add "Alfred"
names.Add "Tim"
names.Add "Richard"

let print s = printfn "%s" s

// Display the contents of the list using the print function.
names.ForEach(Action<string> print)

// The following demonstrates the lambda expression feature of F#
// to display the contents of the list to the console.
names.ForEach(fun s -> printfn "%s" s)

(* This code will produce output similar to the following:
* Bruce
* Alfred
* Tim
* Richard
* Bruce
* Alfred
* Tim
* Richard
*)
Imports System.Collections.Generic

Class Program
    Shared Sub Main()
        Dim names As New List(Of String)
        names.Add("Bruce")
        names.Add("Alfred")
        names.Add("Tim")
        names.Add("Richard")

        ' Display the contents of the list using the Print method.
        names.ForEach(AddressOf Print)
    End Sub

    Shared Sub Print(ByVal s As String)
        Console.WriteLine(s)
    End Sub
End Class

' This code will produce output similar to the following:
' Bruce
' Alfred
' Tim
' Richard

설명

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

참고

매개 변수가 하나 있고 값을 반환하는 메서드를 참조하려면 대신 제네릭 Func<T,TResult> 대리자를 사용합니다.

대리자를 Action<T> 사용하는 경우 메서드를 단일 매개 변수로 캡슐화하는 대리자를 명시적으로 정의할 필요가 없습니다. 예를 들어 다음 코드는 명명 DisplayMessage 된 대리자를 명시적으로 선언하고 해당 대리자 인스턴스에 WriteLine 메서드 또는 메서드에 ShowWindowsMessage 대한 참조를 할당합니다.

#using <System.Windows.Forms.dll>

using namespace System;
using namespace System::Windows::Forms;

public delegate void DisplayMessage(String^ message);

public ref class TestCustomDelegate
{
public:
   static void ShowWindowsMessage(String^ message)
   {
      MessageBox::Show(message);      
   }
};

int main()
{
    DisplayMessage^ messageTarget; 
      
    if (Environment::GetCommandLineArgs()->Length > 1)
       messageTarget = gcnew DisplayMessage(&TestCustomDelegate::ShowWindowsMessage);
    else
       messageTarget = gcnew DisplayMessage(&Console::WriteLine);
    
    messageTarget(L"Hello World!");
    return 0;
}
using System;
using System.Windows.Forms;

delegate void DisplayMessage(string message);

public class TestCustomDelegate
{
   public static void Main()
   {
      DisplayMessage messageTarget;

      if (Environment.GetCommandLineArgs().Length > 1)
         messageTarget = ShowWindowsMessage;
      else
         messageTarget = Console.WriteLine;

      messageTarget("Hello, World!");
   }

   private static void ShowWindowsMessage(string message)
   {
      MessageBox.Show(message);
   }
}
open System
open System.Windows.Forms

type DisplayMessage = delegate of message: string -> unit

let showWindowsMessage message = 
    MessageBox.Show message |> ignore

let messageTarget =
    DisplayMessage(
        if Environment.GetCommandLineArgs().Length > 1 then
            showWindowsMessage
        else
            printfn "%s"
    )

messageTarget.Invoke "Hello, World!"
Delegate Sub DisplayMessage(message As String) 

Module TestCustomDelegate
   Public Sub Main
      Dim messageTarget As DisplayMessage 

      If Environment.GetCommandLineArgs().Length > 1 Then
         messageTarget = AddressOf ShowWindowsMessage
      Else
         messageTarget = AddressOf Console.WriteLine
      End If
      messageTarget("Hello, World!")
   End Sub
   
   Private Sub ShowWindowsMessage(message As String)
      MsgBox(message)
   End Sub   
End Module

다음 예제에서는 인스턴스화하여이 코드를 간소화는 Action<T> 명시적으로 새 대리자를 정의 하 고 명명된 된 메서드를 할당 하는 대신 대리자입니다.

#using <System.Windows.Forms.dll>

using namespace System;
using namespace System::Windows::Forms;

namespace ActionExample
{
   public ref class Message
   {
   public:
      static void ShowWindowsMessage(String^ message)
      {
         MessageBox::Show(message);
      }
   };
}

int main()
{
   Action<String^>^ messageTarget;

   if (Environment::GetCommandLineArgs()->Length > 1)
      messageTarget = gcnew Action<String^>(&ActionExample::Message::ShowWindowsMessage);
   else
      messageTarget = gcnew Action<String^>(&Console::WriteLine);

   messageTarget("Hello, World!");
   return 0;
}
using System;
using System.Windows.Forms;

public class TestAction1
{
   public static void Main()
   {
      Action<string> messageTarget;

      if (Environment.GetCommandLineArgs().Length > 1)
         messageTarget = ShowWindowsMessage;
      else
         messageTarget = Console.WriteLine;

      messageTarget("Hello, World!");
   }

   private static void ShowWindowsMessage(string message)
   {
      MessageBox.Show(message);
   }
}
open System
open System.Windows.Forms

let showWindowsMessage message = 
    MessageBox.Show message |> ignore

let messageTarget =
    Action<string>(
        if Environment.GetCommandLineArgs().Length > 1 then
            showWindowsMessage
        else
            printfn "%s"
    )

messageTarget.Invoke "Hello, World!"
Module TestAction1
   Public Sub Main
      Dim messageTarget As Action(Of String) 

      If Environment.GetCommandLineArgs().Length > 1 Then
         messageTarget = AddressOf ShowWindowsMessage
      Else
         messageTarget = AddressOf Console.WriteLine
      End If
      messageTarget("Hello, World!")
   End Sub
   
   Private Sub ShowWindowsMessage(message As String)
      MsgBox(message)
   End Sub   
End Module

사용할 수도 있습니다는 Action<T> 다음 예제와 같이 C#에서는 무명 메서드로 위임 합니다. (소개 무명 메서드를 참조 하세요 무명 메서드.)

using System;
using System.Windows.Forms;

public class TestAnonMethod
{
   public static void Main()
   {
      Action<string> messageTarget;

      if (Environment.GetCommandLineArgs().Length > 1)
         messageTarget = delegate(string s) { ShowWindowsMessage(s); };
      else
         messageTarget = delegate(string s) { Console.WriteLine(s); };

      messageTarget("Hello, World!");
   }

   private static void ShowWindowsMessage(string message)
   {
      MessageBox.Show(message);
   }
}

람다 식을 할당할 수도 있습니다는 Action<T> 다음 예제와 같이 인스턴스를 위임 합니다. (람다 식에 대 한 소개를 참조 하세요 람다 식.)

using System;
using System.Windows.Forms;

public class TestLambdaExpression
{
   public static void Main()
   {
      Action<string> messageTarget;

      if (Environment.GetCommandLineArgs().Length > 1)
         messageTarget = s => ShowWindowsMessage(s);
      else
         messageTarget = s => Console.WriteLine(s);

      messageTarget("Hello, World!");
   }

   private static void ShowWindowsMessage(string message)
   {
      MessageBox.Show(message);
   }
}
open System
open System.Windows.Forms

let showWindowsMessage message = 
    MessageBox.Show message |> ignore

let messageTarget =
    Action<string>(
        if Environment.GetCommandLineArgs().Length > 1 then
            fun s -> showWindowsMessage s
        else
            fun s -> printfn "%s" s
    )

messageTarget.Invoke "Hello, World!"
Imports System.Windows.Forms

Public Module TestLambdaExpression
   Public Sub Main()
      Dim messageTarget As Action(Of String) 
      
      If Environment.GetCommandLineArgs().Length > 1 Then
         messageTarget = Sub(s) ShowWindowsMessage(s) 
      Else
         messageTarget = Sub(s) ShowConsoleMessage(s)
      End If
      messageTarget("Hello, World!")
   End Sub
      
   Private Function ShowWindowsMessage(message As String) As Integer
      Return MessageBox.Show(message)      
   End Function
   
   Private Function ShowConsoleMessage(message As String) As Integer
      Console.WriteLine(message)
      Return 0
   End Function
End Module

각 메서드와 ForEach 메서드는 ForEach 대리자를 Action<T> 매개 변수로 사용합니다. 대리자가 캡슐화한 메서드를 사용하면 배열 또는 목록의 각 요소에 대해 작업을 수행할 수 있습니다. 이 예제에서는 메서드를 ForEach 사용하여 그림을 제공합니다.

확장 메서드

GetMethodInfo(Delegate)

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

적용 대상

추가 정보