MulticastDelegate MulticastDelegate MulticastDelegate MulticastDelegate Class

Definición

Representa un delegado multidifusión; es decir, un delegado que puede tener más de un elemento en su lista de invocación.Represents a multicast delegate; that is, a delegate that can have more than one element in its invocation list.

public ref class MulticastDelegate abstract : Delegate
[System.Runtime.InteropServices.ComVisible(true)]
[System.Serializable]
public abstract class MulticastDelegate : Delegate
type MulticastDelegate = class
    inherit Delegate
Public MustInherit Class MulticastDelegate
Inherits Delegate
Herencia
MulticastDelegateMulticastDelegateMulticastDelegateMulticastDelegate
Atributos

Ejemplos

En el ejemplo siguiente se define una StringContainerclase,, que incluye una colección de cadenas.The following example defines a class, StringContainer, which includes a collection of strings. Uno de sus miembros es el CheckAndDisplayDelegate delegado, que se usa para mostrar las cadenas almacenadas StringContainer en un objeto que satisfacen determinados criterios.One of its members is the CheckAndDisplayDelegate delegate, which is used to display strings stored in a StringContainer object that satisfy particular criteria. El delegado toma una sola cadena como parámetro y devuelve void (o, en Visual Basic, es un Sub procedimiento).The delegate takes a single string as a parameter and returns void (or, in Visual Basic, it's a Sub procedure). También incluye un método, DisplayAllQualified, que tiene un único parámetro, un CheckAndDisplayDelegate delegado.It also includes a method, DisplayAllQualified, that has a single parameter, a CheckAndDisplayDelegate delegate. Esto permite llamar al método y mostrar un conjunto de cadenas que se filtran en función de los métodos que contiene el delegado.This allows the method to be called and to display a set of strings that are filtered based on the methods that the delegate contains.

En el ejemplo también se define una clase StringExtensionsde utilidad,, que tiene dos métodos:The example also defines a utility class, StringExtensions, that has two methods:

  • ConStart, que muestra las cadenas que comienzan por una consonante.ConStart, which displays strings that begin with a consonant.

  • VowelStart, que muestra las cadenas que comienzan con una vocal.VowelStart, which displays strings that begin with a vowel.

Tenga en cuenta que ambos métodos incluyen un único parámetro de voidcadena y devuelven.Note that both methods include a single string parameter and return void. En otras palabras, ambos métodos se pueden asignar al CheckAndDisplayDelegate delegado.In other words, both methods can be assigned to the CheckAndDisplayDelegate delegate.

El Test.Main método es el punto de entrada de la aplicación.The Test.Main method is the application entry point. Crea una instancia de StringContainer un objeto, lo rellena con cadenas y crea dos CheckAndDisplayDelegate delegados conStart , vowelStarty, que invocan un único método.It instantiates a StringContainer object, populates it with strings, and creates two CheckAndDisplayDelegate delegates, conStart and vowelStart, that invoke a single method. A continuación, llama Delegate.Combine al método para crear multipleDelegates el delegado, que inicialmente contiene ConStart los VowelStart delegados y.It then calls the Delegate.Combine method to create the multipleDelegates delegate, which initially contains the ConStart and VowelStart delegates. Tenga en cuenta que multipleDelegates cuando se invoca el delegado, se muestran todas las cadenas de la colección en su orden original.Note that when the multipleDelegates delegate is invoked, it displays all the strings in the collection in their original order. Esto se debe a que cada letra se pasa por separado a cada delegado, y cada letra cumple los criterios de filtrado de solo uno de los dos delegados.This is because each letter is passed separately to each delegate, and each letter meets the filtering criteria of only one of the two delegates. Por último, después de Delegate.Remove las Delegate.Combinellamadas multipleDelegates a y conStart , contiene dos delegados.Finally, after calls to Delegate.Remove and Delegate.Combine, multipleDelegates contains two conStart delegates. Cuando se invoca, cada cadena StringContainer del objeto se muestra dos veces.When it is invoked, each string in the StringContainer object is displayed twice.

using namespace System;
using namespace System::Collections::Generic;

ref class StringContainer
{
private:
   // A generic list object that holds the strings.
   List<String^>^ container = gcnew List<String^>;

public:
   // Define a delegate to handle string display.
   delegate void CheckAndDisplayDelegate(String^ str);

   // A method that adds more strings to the collection.
   void AddString(String^ str)
   {
      container->Add(str);
   }

   // Iterate through the strings and invoke the method(s) that the delegate points to.
   void DisplayAllQualified(CheckAndDisplayDelegate^ displayDelegate)
   {
      for each (String^ str in container)
         displayDelegate(str);
//       System::Collections::IEnumerator^ myEnum = container->GetEnumerator();
//       while ( myEnum->MoveNext() )
//       {
//          String^ str = safe_cast<String^>(myEnum->Current);
//          displayDelegate(str);
//      }
   }
};

//end of class StringContainer
// This class contains a few sample methods
ref class StringFuncs
{
public:

   // This method prints a String* that it is passed if the String* starts with a vowel
   static void ConStart(String^ str)
   {
      if (  !(str[ 0 ] == 'a' || str[ 0 ] == 'e' || str[ 0 ] == 'i' || str[ 0 ] == 'o' || str[ 0 ] == 'u') )
            Console::WriteLine( str );
   }

   // This method prints a String* that it is passed if the String* starts with a consonant
   static void VowelStart( String^ str )
   {
      if ( (str[ 0 ] == 'a' || str[ 0 ] == 'e' || str[ 0 ] == 'i' || str[ 0 ] == 'o' || str[ 0 ] == 'u') )
            Console::WriteLine( str );
   }
};

// This function demonstrates using Delegates, including using the Remove and
// Combine methods to create and modify delegate combinations.
int main()
{
   // Declare the StringContainer class and add some strings
   StringContainer^ container = gcnew StringContainer;
   container->AddString( "This" );
   container->AddString( "is" );
   container->AddString( "a" );
   container->AddString( "multicast" );
   container->AddString( "delegate" );
   container->AddString( "example" );

// RETURN HERE.
   // Create two delegates individually using different methods
   StringContainer::CheckAndDisplayDelegate^ conStart = gcnew StringContainer::CheckAndDisplayDelegate( StringFuncs::ConStart );
   StringContainer::CheckAndDisplayDelegate^ vowelStart = gcnew StringContainer::CheckAndDisplayDelegate( StringFuncs::VowelStart );

   // Get the list of all delegates assigned to this MulticastDelegate instance. 
   array<Delegate^>^ delegateList = conStart->GetInvocationList();
   Console::WriteLine("conStart contains {0} delegate(s).", delegateList->Length);
   delegateList = vowelStart->GetInvocationList();
   Console::WriteLine("vowelStart contains {0} delegate(s).\n", delegateList->Length );

   // Determine whether the delegates are System::Multicast delegates
   if ( dynamic_cast<System::MulticastDelegate^>(conStart) && dynamic_cast<System::MulticastDelegate^>(vowelStart) )
   {
      Console::WriteLine("conStart and vowelStart are derived from MulticastDelegate.\n");
   }

   // Execute the two delegates.
   Console::WriteLine("Executing the conStart delegate:" );
   container->DisplayAllQualified(conStart);
   Console::WriteLine();
   Console::WriteLine("Executing the vowelStart delegate:" );
   container->DisplayAllQualified(vowelStart);

   // Create a new MulticastDelegate and call Combine to add two delegates.
   StringContainer::CheckAndDisplayDelegate^ multipleDelegates =
           dynamic_cast<StringContainer::CheckAndDisplayDelegate^>(Delegate::Combine(conStart, vowelStart));

   // How many delegates does multipleDelegates contain?
   delegateList = multipleDelegates->GetInvocationList();
   Console::WriteLine("\nmultipleDelegates contains {0} delegates.\n", 
                      delegateList->Length );

   //       // Pass this multicast delegate to DisplayAllQualified.
   Console::WriteLine("Executing the multipleDelegate delegate.");
   container->DisplayAllQualified(multipleDelegates);
   // Call remove and combine to change the contained delegates.
   multipleDelegates = dynamic_cast<StringContainer::CheckAndDisplayDelegate^>
                      (Delegate::Remove(multipleDelegates, vowelStart));
   multipleDelegates = dynamic_cast<StringContainer::CheckAndDisplayDelegate^>
                      (Delegate::Combine(multipleDelegates, conStart));

   // Pass multipleDelegates to DisplayAllQualified again.
   Console::WriteLine("\nExecuting the multipleDelegate delegate with two conStart delegates:");
   container->DisplayAllQualified(multipleDelegates);
} 
// The example displays the following output:
//    conStart contains 1 delegate(s).
//    vowelStart contains 1 delegate(s).
//    
//    conStart and vowelStart are derived from MulticastDelegate.
//    
//    Executing the conStart delegate:
//    This
//    multicast
//    delegate
//    
//    Executing the vowelStart delegate:
//    is
//    a
//    example
//    
//    
//    multipleDelegates contains 2 delegates.
//    
//    Executing the multipleDelegate delegate.
//    This
//    is
//    a
//    multicast
//    delegate
//    example
//    
//    Executing the multipleDelegate delegate with two conStart delegates:
//    This
//    This
//    multicast
//    multicast
//    delegate
//    delegate
using System;
using System.Collections.Generic;

class StringContainer
{
   // Define a delegate to handle string display. 
   public delegate void CheckAndDisplayDelegate(string str);

   // A generic list object that holds the strings. 
   private List<String> container = new List<String>();

   // A method that adds strings to the collection. 
   public void AddString(string str) 
   {
      container.Add(str);
   }

   // Iterate through the strings and invoke the method(s) that the delegate points to. 
   public void DisplayAllQualified(CheckAndDisplayDelegate displayDelegate) 
   {
      foreach (var str in container) {
         displayDelegate(str);
      }
   }
 }    

// This class defines some methods to display strings. 
class StringExtensions
{
   // Display a string if it starts with a consonant. 
   public static void ConStart(string str) 
   {
      if (!(str[0]=='a'||str[0]=='e'||str[0]=='i'||str[0]=='o'||str[0]=='u'))
          Console.WriteLine(str);
   }

   // Display a string if it starts with a vowel.
   public static void VowelStart(string str) 
   {
      if ((str[0]=='a'||str[0]=='e'||str[0]=='i'||str[0]=='o'||str[0]=='u'))
          Console.WriteLine(str);
   }
}

// Demonstrate the use of delegates, including the Remove and 
// Combine methods to create and modify delegate combinations. 
class Test
{
   static public void Main()
   {
      // Declare the StringContainer class and add some strings
      StringContainer container = new StringContainer();
      container.AddString("This");
      container.AddString("is");
      container.AddString("a");
      container.AddString("multicast");
      container.AddString("delegate");
      container.AddString("example");

      // Create two delegates individually using different methods.
      StringContainer.CheckAndDisplayDelegate conStart = StringExtensions.ConStart;
      StringContainer.CheckAndDisplayDelegate vowelStart = StringExtensions.VowelStart;

      // Get the list of all delegates assigned to this MulticastDelegate instance. 
      Delegate[] delegateList = conStart.GetInvocationList();
      Console.WriteLine("conStart contains {0} delegate(s).", delegateList.Length);
      delegateList = vowelStart.GetInvocationList();
      Console.WriteLine("vowelStart contains {0} delegate(s).\n", delegateList.Length);

      // Determine whether the delegates are System.Multicast delegates. 
      if (conStart is System.MulticastDelegate && vowelStart is System.MulticastDelegate) 
          Console.WriteLine("conStart and vowelStart are derived from MulticastDelegate.\n");

      // Execute the two delegates.
      Console.WriteLine("Executing the conStart delegate:");
      container.DisplayAllQualified(conStart);
      Console.WriteLine();
      Console.WriteLine("Executing the vowelStart delegate:");
      container.DisplayAllQualified(vowelStart);
      Console.WriteLine();
      
      // Create a new MulticastDelegate and call Combine to add two delegates.
      StringContainer.CheckAndDisplayDelegate multipleDelegates = 
            (StringContainer.CheckAndDisplayDelegate) Delegate.Combine(conStart, vowelStart);

      // How many delegates does multipleDelegates contain?
      delegateList = multipleDelegates.GetInvocationList();
      Console.WriteLine("\nmultipleDelegates contains {0} delegates.\n",
                        delegateList.Length);

      // Pass this multicast delegate to DisplayAllQualified.
      Console.WriteLine("Executing the multipleDelegate delegate.");
      container.DisplayAllQualified(multipleDelegates);

      // Call remove and combine to change the contained delegates.
      multipleDelegates = (StringContainer.CheckAndDisplayDelegate) Delegate.Remove(multipleDelegates, vowelStart);
      multipleDelegates = (StringContainer.CheckAndDisplayDelegate) Delegate.Combine(multipleDelegates, conStart);

      // Pass multipleDelegates to DisplayAllQualified again.
      Console.WriteLine("\nExecuting the multipleDelegate delegate with two conStart delegates:");
      container.DisplayAllQualified(multipleDelegates);
   }
}
// The example displays the following output:
//    conStart contains 1 delegate(s).
//    vowelStart contains 1 delegate(s).
//    
//    conStart and vowelStart are derived from MulticastDelegate.
//    
//    Executing the conStart delegate:
//    This
//    multicast
//    delegate
//    
//    Executing the vowelStart delegate:
//    is
//    a
//    example
//    
//    
//    multipleDelegates contains 2 delegates.
//    
//    Executing the multipleDelegate delegate.
//    This
//    is
//    a
//    multicast
//    delegate
//    example
//    
//    Executing the multipleDelegate delegate with two conStart delegates:
//    This
//    This
//    multicast
//    multicast
//    delegate
//    delegate
Imports System.Collections.Generic

Class StringContainer
    ' Define a delegate to handle string display. 
    Delegate Sub CheckAndPrintDelegate(ByVal str As String)

    ' A generic list object that holds the strings.
    Private container As New List(Of String)()

     ' A method that adds strings to the collection. 
     Public Sub AddString(ByVal s As String)
        container.Add(s)
    End Sub

    ' Iterate through the strings and invoke the method(s) that the delegate points to.
    Public Sub DisplayAllQualified(ByVal displayDelegate As CheckAndPrintDelegate)
        For Each s In container
            displayDelegate(s)
        Next
    End Sub
End Class

' This class defines some methods to display strings. 
Class StringExtensions
    ' Display a string if it starts with a consonant. 
    Public Shared Sub ConStart(ByVal str As String)
        If Not (str.Chars(0) = "a"c Or str.Chars(0) = "e"c Or str.Chars(0) = "i"c _ 
                Or str.Chars(0) = "o"c Or str.Chars(0) = "u"c) Then
            Console.WriteLine(str)
        End If
    End Sub 

    ' Display a string if it starts with a vowel.
    Public Shared Sub VowelStart(ByVal str As String)
        If (str.Chars(0) = "a"c Or str.Chars(0) = "e"c Or str.Chars(0) = "i"c _
            Or str.Chars(0) = "o"c Or str.Chars(0) = "u"c) Then
            Console.WriteLine(str)
        End If
    End Sub 
End Class 

' Demonstrate the use of delegates, including the Remove and 
' Combine methods to create and modify delegate combinations. 
Class Test
    Public Shared Sub Main()
        ' Declare the StringContainer class and add some strings
        Dim container As New StringContainer()
        container.AddString("this")
        container.AddString("is")
        container.AddString("a")
        container.AddString("multicast")
        container.AddString("delegate")
        container.AddString("example")

        ' Create two delegates individually using different methods.
        Dim constart As StringContainer.CheckAndPrintDelegate = AddressOf StringExtensions.ConStart
        Dim vowelStart As StringContainer.CheckAndPrintDelegate = AddressOf StringExtensions.VowelStart

        ' Get the list of all delegates assigned to this MulticastDelegate instance. 
        Dim delegateList() As [Delegate] = conStart.GetInvocationList()
        Console.WriteLine("conStart contains {0} delegate(s).", delegateList.Length)
        delegateList = vowelStart.GetInvocationList()
        Console.WriteLine("vowelStart contains {0} delegate(s).", delegateList.Length)
        Console.WriteLine()
        
        ' Determine whether the delegates are System.Multicast delegates
        If TypeOf conStart Is System.MulticastDelegate And TypeOf vowelStart Is System.MulticastDelegate Then
            Console.WriteLine("conStart and vowelStart are derived from MulticastDelegate.")
            Console.WriteLine()
        End If

        ' Run the two single delegates one after the other.
        Console.WriteLine("Executing the conStart delegate:")
        container.DisplayAllQualified(conStart)
        Console.WriteLine("Executing the vowelStart delegate:")
        container.DisplayAllQualified(vowelStart)
        Console.WriteLine()

        ' Create a new MulticastDelegate and call Combine to add two delegates.
        Dim multipleDelegates As StringContainer.CheckAndPrintDelegate = 
                  CType([Delegate].Combine(conStart, vowelStart), 
                  StringContainer.CheckAndPrintDelegate)

        ' How many delegates does multipleDelegates contain?
        delegateList = multipleDelegates.GetInvocationList()
        Console.WriteLine("{1}multipleDelegates contains {0} delegates.{1}",
                          delegateList.Length, vbCrLf)

        ' Pass this mulitcast delegate to DisplayAllQualified.
        Console.WriteLine("Executing the multipleDelegate delegate.")
        container.DisplayAllQualified(multipleDelegates)

        ' Call remove and combine to change the contained delegates.
        multipleDelegates = CType([Delegate].Remove(multipleDelegates, vowelStart), 
                            StringContainer.CheckAndPrintDelegate)
        multipleDelegates = CType([Delegate].Combine(multipleDelegates, conStart), 
                            StringContainer.CheckAndPrintDelegate)

        ' Pass multipleDelegates to DisplayAllQualified again.
        Console.WriteLine()
        Console.WriteLine("Executing the multipleDelegate delegate with two conStart delegates:")
        container.DisplayAllQualified(multipleDelegates)
    End Sub 
End Class 
' The example displays the following output:
'    conStart contains 1 delegate(s).
'    vowelStart contains 1 delegate(s).
'    
'    conStart and vowelStart are derived from MulticastDelegate.
'    
'    Executing the conStart delegate:
'    This
'    multicast
'    delegate
'    
'    Executing the vowelStart delegate:
'    is
'    a
'    example
'    
'    
'    multipleDelegates contains 2 delegates.
'    
'    Executing the multipleDelegate delegate.
'    This
'    is
'    a
'    multicast
'    delegate
'    example
'    
'    Executing the multipleDelegate delegate with two conStart delegates:
'    This
'    This
'    multicast
'    multicast
'    delegate
'    delegate

Comentarios

MulticastDelegatees una clase especial.MulticastDelegate is a special class. Los compiladores y otras herramientas se pueden derivar de esta clase, pero no se pueden derivar de él explícitamente.Compilers and other tools can derive from this class, but you cannot derive from it explicitly. Lo mismo se aplica a la Delegate clase.The same is true of the Delegate class.

Además de los métodos que heredan los tipos de MulticastDelegatedelegado, el Common Language Runtime proporciona dos métodos especiales BeginInvoke : EndInvokey.In addition to the methods that delegate types inherit from MulticastDelegate, the common language runtime provides two special methods: BeginInvoke and EndInvoke. Para obtener más información sobre estos métodos, consulte llamar a métodos sincrónicos de forma asincrónica.For more information about these methods, see Calling Synchronous Methods Asynchronously.

Un MulticastDelegate tiene una lista vinculada de delegados, denominada lista de invocación, que consta de uno o varios elementos.A MulticastDelegate has a linked list of delegates, called an invocation list, consisting of one or more elements. Cuando se invoca un delegado de multidifusión, se llama a los delegados de la lista de invocación de forma sincrónica en el orden en que aparecen.When a multicast delegate is invoked, the delegates in the invocation list are called synchronously in the order in which they appear. Si se produce un error durante la ejecución de la lista, se produce una excepción.If an error occurs during execution of the list then an exception is thrown.

Constructores

MulticastDelegate(Object, String) MulticastDelegate(Object, String) MulticastDelegate(Object, String) MulticastDelegate(Object, String)

Inicializa una nueva instancia de la clase MulticastDelegate.Initializes a new instance of the MulticastDelegate class.

MulticastDelegate(Type, String) MulticastDelegate(Type, String) MulticastDelegate(Type, String) MulticastDelegate(Type, String)

Inicializa una nueva instancia de la clase MulticastDelegate.Initializes a new instance of the MulticastDelegate class.

Métodos

Clone() Clone() Clone() Clone()

Crea una copia superficial del delegado.Creates a shallow copy of the delegate.

(Inherited from Delegate)
CombineImpl(Delegate) CombineImpl(Delegate) CombineImpl(Delegate) CombineImpl(Delegate)

Combina este Delegate con el Delegate especificado para formar un nuevo delegado.Combines this Delegate with the specified Delegate to form a new delegate.

DynamicInvoke(Object[]) DynamicInvoke(Object[]) DynamicInvoke(Object[]) DynamicInvoke(Object[])

Invoca dinámicamente (en tiempo de ejecución) al método representado por el delegado actual.Dynamically invokes (late-bound) the method represented by the current delegate.

(Inherited from Delegate)
DynamicInvokeImpl(Object[]) DynamicInvokeImpl(Object[]) DynamicInvokeImpl(Object[]) DynamicInvokeImpl(Object[])

Procesa toda la lista de invocación.Processes the full invocation list.

Equals(Object) Equals(Object) Equals(Object) Equals(Object)

Determina si este delegado multidifusión y el objeto especificado son iguales.Determines whether this multicast delegate and the specified object are equal.

GetHashCode() GetHashCode() GetHashCode() GetHashCode()

Devuelve el código hash de esta instancia.Returns the hash code for this instance.

GetInvocationList() GetInvocationList() GetInvocationList() GetInvocationList()

Devuelve la lista de invocación de este delegado multidifusión, en el orden de invocación.Returns the invocation list of this multicast delegate, in invocation order.

GetMethodImpl() GetMethodImpl() GetMethodImpl() GetMethodImpl()

Devuelve un método estático representado por el MulticastDelegate actual.Returns a static method represented by the current MulticastDelegate.

GetObjectData(SerializationInfo, StreamingContext) GetObjectData(SerializationInfo, StreamingContext) GetObjectData(SerializationInfo, StreamingContext) GetObjectData(SerializationInfo, StreamingContext)

Rellena un objeto SerializationInfo con todos los datos necesarios para serializar la instancia.Populates a SerializationInfo object with all the data needed to serialize this instance.

GetType() GetType() GetType() GetType()

Obtiene el Type de la instancia actual.Gets the Type of the current instance.

(Inherited from Object)
MemberwiseClone() MemberwiseClone() MemberwiseClone() MemberwiseClone()

Crea una copia superficial del objeto Object actual.Creates a shallow copy of the current Object.

(Inherited from Object)
RemoveImpl(Delegate) RemoveImpl(Delegate) RemoveImpl(Delegate) RemoveImpl(Delegate)

Quita un elemento de la lista de invocación de este MulticastDelegate que sea igual al delegado especificado.Removes an element from the invocation list of this MulticastDelegate that is equal to the specified delegate.

ToString() ToString() ToString() ToString()

Devuelve una cadena que representa el objeto actual.Returns a string that represents the current object.

(Inherited from Object)

Operadores

Equality(MulticastDelegate, MulticastDelegate) Equality(MulticastDelegate, MulticastDelegate) Equality(MulticastDelegate, MulticastDelegate) Equality(MulticastDelegate, MulticastDelegate)

Determina si los dos objetos MulticastDelegate son iguales.Determines whether two MulticastDelegate objects are equal.

Inequality(MulticastDelegate, MulticastDelegate) Inequality(MulticastDelegate, MulticastDelegate) Inequality(MulticastDelegate, MulticastDelegate) Inequality(MulticastDelegate, MulticastDelegate)

Determina si dos objetos MulticastDelegate no son iguales.Determines whether two MulticastDelegate objects are not equal.

Propiedades

Method Method Method Method

Obtiene el método representado por el delegado.Gets the method represented by the delegate.

(Inherited from Delegate)
Target Target Target Target

Obtiene la instancia de clase donde el delegado actual invoca al método de instancia.Gets the class instance on which the current delegate invokes the instance method.

(Inherited from Delegate)

Métodos de extensión

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

Obtiene un objeto que representa el método representado por el delegado especificado.Gets an object that represents the method represented by the specified delegate.

Se aplica a