Action Delegate 委托方法

注意:本内容来自:https://docs.microsoft.com/zh-cn/dotnet/api/system.action-1?view=netframework-4.7.2#定义

Action ActionAction Delegate

定义

命名空间:

SystemSystem SystemSystem

Assemblies:

System.Runtime.dll, mscorlib.dll, netstandard.dll

封装一个方法,该方法只有一个参数并且不返回值。 Encapsulates a method that has a single parameter and does not return a value.

本文内容

  1. 定义
  2. 示例
  3. 注解
  4. 适用于
  5. 另请参阅
generic 
public delegate void Action(T obj);

C#复制

public delegate void Action(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.

继承

ObjectObjectObjectObject

DelegateDelegateDelegateDelegate

ActionActionActionAction

示例

下面的示例演示如何将Action要打印的内容委托List对象。The following example demonstrates the use of the Action delegate to print the contents of a List 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变量。Note that the example does not explicitly declare an Action variable. 相反,它将传递到方法采用单个参数和与未返回到的值的引用List.ForEach方法,其单个参数是Action委托。Instead, it passes a reference to a method that takes a single parameter and that does not return a value to the List.ForEach method, whose single parameter is an Action delegate. 同样,在 C# 示例中,Action委托不显式实例化,因为匿名方法的签名匹配的签名Action委托所需的List.ForEach方法。Similarly, in the C# example, an Action delegate is not explicitly instantiated because the signature of the anonymous method matches the signature of the Action delegate that is expected by the List.ForEach method.

C#复制

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        List names = new List();
        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委托作为参数传递方法,而无需显式声明自定义委托。You can use the Action 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改为委托。To reference a method that has one parameter and returns a value, use the generic Func delegate instead.

当你使用Action委托时,您无需显式定义用于封装具有单个参数的方法的委托。When you use the Action 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 

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

C#复制

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而不是显式定义一个新委托,并为其赋值命名的方法的委托。The following example simplifies this code by instantiating the Action delegate instead of explicitly defining a new delegate and assigning a named method to it.

#using 

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^ messageTarget;

   if (Environment::GetCommandLineArgs()->Length > 1)
      messageTarget = gcnew Action(&ActionExample::Message::ShowWindowsMessage);
   else
      messageTarget = gcnew Action(&Console::WriteLine);

   messageTarget("Hello, World!");
   return 0;
}

C#复制

using System;
using System.Windows.Forms;

public class TestAction1
{
   public static void Main()
   {
      Action 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委托与匿名方法在 C# 中,如以下示例所示。You can also use the Action delegate with anonymous methods in C#, as the following example illustrates. (有关匿名方法的介绍,请参阅匿名方法。)(For an introduction to anonymous methods, see Anonymous Methods.)

C#复制

using System;
using System.Windows.Forms;

public class TestAnonMethod
{
   public static void Main()
   {
      Action 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委托实例,如以下示例所示。You can also assign a lambda expression to an Action delegate instance, as the following example illustrates. (有关 lambda 表达式的简介,请参阅Lambda 表达式。)(For an introduction to lambda expressions, see Lambda Expressions.)

C#复制

using System;
using System.Windows.Forms;

public class TestLambdaExpression
{
   public static void Main()
   {
      Action 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

ForEach并ForEach每个方法均采用Action委托作为参数。The ForEach and ForEach methods each take an Action 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.

适用于

.NET Core

2.22.12.01.11.0

.NET Framework

4.84.7.24.7.14.74.6.24.6.14.64.5.24.5.14.54.03.53.02.0

.NET Standard

2.01.61.51.41.31.21.11.0

Xamarin.Android

7.1

Xamarin.iOS

10.8

Xamarin.Mac

3.0

另请参阅

  • Func

你可能感兴趣的:(Delegate)