Action<T> 委托

定义

封装一个方法,该方法只有一个参数并且不返回值。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);
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

此委托封装的方法的参数类型。The type of the parameter of the method that this delegate encapsulates.

这是逆变类型参数。 即,可以使用指定的类型,也可以使用派生程度较低的任何类型。 有关协变和逆变的详细信息,请参阅泛型中的协变和逆变

参数

obj
T

此委托封装的方法的参数。The parameter of the method that this delegate encapsulates.

继承
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>.ForEachSimilarly, 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.

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
*/
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。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)

获取指示指定委托表示的方法的对象。Gets an object that represents the method represented by the specified delegate.

适用于

另请参阅