Action<T> Delegat

Definicja

Hermetyzuje metodę, która ma jeden parametr i nie zwraca wartości.

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)

Parametry typu

T

Typ parametru metody, którą ten delegat hermetyzuje.

Ten parametr typu jest kontrawariantny. Oznacza to, że możesz użyć typu, który został przez Ciebie określony, lub dowolnego typu, który jest mniej pochodny. Aby uzyskać więcej informacji o kowariancji i kontrawariancji, zobacz Kowariancja i kontrawariancja w typach ogólnych.

Parametry

obj
T

Parametr metody, którą ten delegat hermetyzuje.

Przykłady

W poniższym przykładzie pokazano użycie delegata Action<T> do drukowania zawartości List<T> obiektu. W tym przykładzie Print metoda służy do wyświetlania zawartości listy w konsoli programu . Ponadto w przykładzie języka C# pokazano również użycie metod anonimowych do wyświetlania zawartości konsoli. Należy pamiętać, że przykład nie deklaruje jawnie zmiennej Action<T> . Zamiast tego przekazuje odwołanie do metody, która przyjmuje pojedynczy parametr i nie zwraca wartości do List<T>.ForEach metody, której pojedynczy parametr jest delegatem Action<T> . Podobnie w przykładzie Action<T> języka C# delegat nie jest jawnie tworzone, ponieważ podpis metody anonimowej jest zgodny z podpisem Action<T> delegata oczekiwanego przez metodę List<T>.ForEach .

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

Uwagi

Możesz użyć delegata Action<T> , aby przekazać metodę jako parametr bez jawnego deklarowania delegata niestandardowego. Metoda hermetyzowana musi odpowiadać sygnaturze metody zdefiniowanej przez ten delegat. Oznacza to, że metoda hermetyzowana musi mieć jeden parametr przekazywany do niego według wartości i nie może zwracać wartości. (W języku C#metoda musi zwrócić wartość void. W Visual Basic musi być zdefiniowany przez Sub...End Sub Konstruowania. Może to być również metoda zwracająca wartość, która jest ignorowana. Zazwyczaj taka metoda jest używana do wykonywania operacji.

Uwaga

Aby odwołać się do metody, która ma jeden parametr i zwraca wartość, należy zamiast tego użyć delegata ogólnego Func<T,TResult> .

Jeśli używasz delegata Action<T> , nie musisz jawnie definiować delegata, który hermetyzuje metodę z pojedynczym parametrem. Na przykład poniższy kod jawnie deklaruje delegata o nazwie DisplayMessage i przypisuje odwołanie do metody lub metody do WriteLine wystąpienia delegata 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

Poniższy przykład upraszcza ten kod przez utworzenie wystąpienia delegata Action<T> zamiast jawnego zdefiniowania nowego delegata i przypisania do niego nazwanej metody.

#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

Możesz również użyć delegata Action<T> z metodami anonimowymi w języku C#, jak pokazano w poniższym przykładzie. (Aby zapoznać się z wprowadzeniem do metod anonimowych, zobacz Metody anonimowe).

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

Możesz również przypisać wyrażenie lambda do Action<T> wystąpienia delegata, jak pokazano w poniższym przykładzie. (Aby zapoznać się z wprowadzeniem do wyrażeń lambda, zobacz Wyrażenia lambda).

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

Metody ForEach i ForEach przyjmują delegata Action<T> jako parametr. Metoda hermetyzowana przez delegata umożliwia wykonanie akcji na każdym elemplecie w tablicy lub na liście. W przykładzie użyto metody w ForEach celu udostępnienia ilustracji.

Metody rozszerzania

GetMethodInfo(Delegate)

Pobiera obiekt reprezentujący metodę reprezentowaną przez określonego delegata.

Dotyczy

Zobacz też