Action(T) Delegado
TOC
Collapse the table of content
Expand the table of content
Este artículo se tradujo automáticamente. Para ver el artículo en inglés, active la casilla Inglés. Además, puede mostrar el texto en inglés en una ventana emergente si mueve el puntero del mouse sobre el texto.
Traducción
Inglés

Action<T> (Delegado)

 

Encapsula un método que tiene un solo parámetro y no devuelve un valor.

Para examinar el código fuente de .NET Framework para este tipo, vea el origen de referencia.

Espacio de nombres:   System
Ensamblado:  mscorlib (en mscorlib.dll)

public delegate void Action<in T>(
	T obj
)

Parámetros

obj

Parámetro del método que este delegado encapsula.

Parámetros de tipo

T

Tipo de parámetro del método que este delegado encapsula.

System_CAPS_noteNota

To view the .NET Framework source code for this type, see the Reference Source.You can browse through the source code online, download the reference for offline viewing, and step through the sources (including patches and updates) during debugging; see instructions.

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.(In C#, the method must return void.In 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.

System_CAPS_noteNota

To reference a method that has one parameter and returns a value, use the generic Func<T, TResult> delegate instead.

When you use the Action<T> delegate, you do not have to explicitly define a delegate that encapsulates a method with a single parameter.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;
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);      
   }
}

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

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 Métodos anónimos (Guía de programación de C#).)

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

You can also assign a lambda expression to an Action<T> delegate instance, as the following example illustrates.(For an introduction to lambda expressions, see Expresiones lambda (Guía de programación de C#).)

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

The ForEach and ForEach<T> 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.The example uses the ForEach method to provide an illustration.

The following example demonstrates the use of the Action<T> delegate to print the contents of a List<T> object.In this example, the Print method is used to display the contents of the list to the console.In addition, the C# example also demonstrates the use of anonymous methods to display the contents to the console.Note that the example does not explicitly declare an Action<T> variable.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.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
 */

Universal Windows Platform
Disponible desde 4.5
.NET Framework
Disponible desde 2.0
Portable Class Library
Compatible con: portable .NET platforms
Silverlight
Disponible desde 2.0
Windows Phone Silverlight
Disponible desde 7.0
Windows Phone
Disponible desde 8.1
Volver al principio
Mostrar:
© 2016 Microsoft