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>委托不显式实例化,因为匿名方法的签名匹配的签名Action<T>委托所需的List<T>.ForEach方法。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
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

ForEachForEach每个方法均采用Action<T>委托作为参数。The 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.

适用于

另请参阅