Action<T> Action<T> Action<T> Action<T> Delegate

定義

封裝具有單一參數的方法,並且不會傳回值。Encapsulates a method that has a single parameter and does not return a value.

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

類型參數

T

這個委派所封裝之方法的參數型別。The type of the parameter of the method that this delegate encapsulates.

參數

obj

這個委派所封裝之方法的參數。The parameter of the method that this delegate encapsulates.

繼承
Action<T>Action<T>Action<T>Action<T>

範例

下列範例示範如何使用Action<T>委派來列印List<T>物件的內容。The following example demonstrates the use of the Action<T> delegate to print the contents of a List<T> object. 在此範例中, Print方法是用來將清單的內容顯示到主控台。In this example, the Print method is used to display the contents of the list to the console. 此外, 此C#範例也會示範如何使用匿名方法, 將內容顯示在主控台中。In addition, the C# example also demonstrates the use of anonymous methods to display the contents to the console. 請注意, 此範例不會明確Action<T>宣告變數。Note that the example does not explicitly declare an Action<T> variable. 相反地, 它會將參考傳遞給採用單一參數的方法, 而且不會將值傳回給List<T>.ForEach方法, 其單一參數Action<T>為委派。Instead, it passes a reference to a method that takes a single parameter and that does not return a value to the List<T>.ForEach method, whose single parameter is an Action<T> delegate. 同樣地, 在C#此範例Action<T>中, 委派並未明確具現化, 因為匿名方法的簽章與List<T>.ForEach方法所Action<T>預期的委派簽章相符。Similarly, in the C# example, an Action<T> delegate is not explicitly instantiated because the signature of the anonymous method matches the signature of the Action<T> delegate that is expected by the List<T>.ForEach method.

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        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);
        });
    }

    private static void Print(string s)
    {
        Console.WriteLine(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>委派將方法當做參數傳遞, 而不需要明確宣告自訂委派。You can use the Action<T> delegate to pass a method as a parameter without explicitly declaring a custom delegate. 封裝的方法必須對應到此委派所定義的方法簽章。The encapsulated method must correspond to the method signature that is defined by this delegate. 這表示封裝的方法必須有一個以傳值方式傳遞給它的參數, 而且它不能傳回值。This means that the encapsulated method must have one parameter that is passed to it by value, and it must not return a value. (在C#中, 方法必須void傳回。(In C#, the method must return void. 在 Visual Basic 中, 它必須由Sub...End SubIn Visual Basic, it must be defined by the SubEnd Sub 建構.construct. 它也可以是傳回已忽略值的方法)。一般來說, 這種方法是用來執行作業。It can also be a method that returns a value that is ignored.) Typically, such a method is used to perform an operation.

注意

若要參考具有一個參數並傳回值的方法, 請改用泛型Func<T,TResult>委派。To reference a method that has one parameter and returns a value, use the generic Func<T,TResult> delegate instead.

當您使用Action<T>委派時, 您不需要明確地定義使用單一參數來封裝方法的委派。When you use the Action<T> delegate, you do not have to explicitly define a delegate that encapsulates a method with a single parameter. 例如, 下列程式碼會明確宣告名為DisplayMessage的委派, 並將WriteLine方法或ShowWindowsMessage方法的參考指派給其委派實例。For example, the following code explicitly declares a delegate named DisplayMessage and assigns a reference to either the WriteLine method or the ShowWindowsMessage method to its delegate instance.

#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);      
   }
}
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>委派來簡化此程式碼, 而不是明確定義新的委派, 並將命名的方法指派給它。The following example simplifies this code by instantiating the Action<T> delegate instead of explicitly defining a new delegate and assigning a named method to it.

#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);      
   }
}
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#使用具有匿名方法的委派, 如下列範例所示。You can also use the Action<T> delegate with anonymous methods in C#, as the following example illustrates. (如需匿名方法的簡介, 請參閱匿名方法)。(For an introduction to anonymous methods, see Anonymous Methods.)

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

您也可以將 lambda 運算式指派給Action<T>委派實例, 如下列範例所示。You can also assign a lambda expression to an Action<T> delegate instance, as the following example illustrates. (如需 lambda 運算式的簡介, 請參閱Lambda 運算式)。(For an introduction to lambda expressions, see Lambda Expressions.)

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

和方法各自接受Action<T>委派做為參數。 ForEach ForEachThe ForEach and ForEach methods each take an Action<T> delegate as a parameter. 委派所封裝的方法可讓您在陣列或清單中的每個元素上執行動作。The method encapsulated by the delegate allows you to perform an action on each element in the array or list. 此範例會使用ForEach方法來提供圖例。The example uses the ForEach method to provide an illustration.

擴充方法

GetMethodInfo(Delegate) GetMethodInfo(Delegate) GetMethodInfo(Delegate) GetMethodInfo(Delegate)

取得表示特定委派所代表之方法的物件。Gets an object that represents the method represented by the specified delegate.

適用於

另請參閱