Action<T> 대리자
정의
중요
일부 정보는 릴리스되기 전에 상당 부분 수정될 수 있는 시험판 제품과 관련이 있습니다. Microsoft는 여기에 제공된 정보에 대해 어떠한 명시적이거나 묵시적인 보증도 하지 않습니다.
단일 매개 변수가 있고 값을 반환하지 않는 메서드를 캡슐화합니다.
generic <typename T>
public delegate void Action(T obj);
public delegate void Action<in T>(T obj);
public delegate void Action<in T>(T obj) where T : allows ref struct;
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 대리자를 명시적으로 선언하고 메서드 또는 ShowWindowsMessage 메서드에 WriteLine 대한 참조를 해당 대리자 인스턴스에 할당합니다.
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;
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
다음 예제와 같이 C#에서 익명 메서드와 함께 대리자를 사용할 Action<T> 수도 있습니다. (익명 메서드에 대한 소개는 익명 메서드를 참조하세요.)
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 사용하여 그림을 제공합니다.
확장명 메서드
| Name | Description |
|---|---|
| GetMethodInfo(Delegate) |
지정된 대리자가 나타내는 메서드를 나타내는 개체를 가져옵니다. |