MulticastDelegate Classe
Définition
Important
Certaines informations portent sur la préversion du produit qui est susceptible d’être en grande partie modifiée avant sa publication. Microsoft exclut toute garantie, expresse ou implicite, concernant les informations fournies ici.
Représente un délégué multidiffusion ; autrement dit, un délégué pouvant avoir plusieurs éléments dans sa liste d’appel.
public ref class MulticastDelegate abstract : Delegate
public abstract class MulticastDelegate : Delegate
[System.Serializable]
public abstract class MulticastDelegate : Delegate
[System.Serializable]
[System.Runtime.InteropServices.ComVisible(true)]
public abstract class MulticastDelegate : Delegate
type MulticastDelegate = class
inherit Delegate
[<System.Serializable>]
type MulticastDelegate = class
inherit Delegate
[<System.Serializable>]
[<System.Runtime.InteropServices.ComVisible(true)>]
type MulticastDelegate = class
inherit Delegate
Public MustInherit Class MulticastDelegate
Inherits Delegate
- Héritage
- Attributs
Exemples
L’exemple suivant définit une classe, StringContainer
, qui inclut une collection de chaînes. L’un de ses membres est le délégué CheckAndDisplayDelegate
, qui est utilisé pour afficher des chaînes stockées dans un objet StringContainer
qui répondent à des critères particuliers. Le délégué prend une chaîne unique en tant que paramètre et retourne void
(ou, en Visual Basic, il s’agit d’une procédure Sub
). Il inclut également une méthode, DisplayAllQualified
, qui a un paramètre unique, un délégué CheckAndDisplayDelegate
. Cela permet à la méthode d’être appelée et d’afficher un ensemble de chaînes filtrées en fonction des méthodes que le délégué contient.
L’exemple définit également une classe utilitaire, StringExtensions
, qui a deux méthodes :
ConStart
, qui affiche des chaînes commençant par une consonne.VowelStart
, qui affiche des chaînes commençant par une voyelle.
Notez que les deux méthodes incluent un paramètre de chaîne unique et retournent void
. En d’autres termes, les deux méthodes peuvent être affectées au délégué CheckAndDisplayDelegate
.
La méthode Test.Main
est le point d’entrée de l’application. Il instancie un objet StringContainer
, le remplit avec des chaînes et crée deux délégués CheckAndDisplayDelegate
, conStart
et vowelStart
, qui appellent une méthode unique. Il appelle ensuite la méthode Delegate.Combine pour créer le délégué multipleDelegates
, qui contient initialement les délégués ConStart
et VowelStart
. Notez que lorsque le délégué multipleDelegates
est appelé, il affiche toutes les chaînes de la collection dans leur ordre d’origine. Cela est dû au fait que chaque lettre est transmise séparément à chaque délégué, et chaque lettre répond aux critères de filtrage d’un seul des deux délégués. Enfin, après les appels à Delegate.Remove et Delegate.Combine, multipleDelegates
contient deux délégués conStart
. Lorsqu’elle est appelée, chaque chaîne de l’objet StringContainer
s’affiche deux fois.
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
module Test
open System
// Define a delegate to handle string display.
type CheckAndDisplayDelegate = delegate of string -> unit
type StringContainer() =
// A generic ResizeArray object that holds the strings.
let container = ResizeArray()
// A method that adds strings to the collection.
member _.AddString(str) =
container.Add str
// Iterate through the strings and invoke the method(s) that the delegate points to.
member _.DisplayAllQualified(displayDelegate: CheckAndDisplayDelegate) =
for str in container do
displayDelegate.Invoke str
// This module defines some functions to display strings.
module StringExtensions =
// Display a string if it starts with a consonant.
let conStart (str: string) =
match str[0] with
| 'a' | 'e' | 'i' | 'o' | 'u' -> ()
| _ -> printfn $"{str}"
// Display a string if it starts with a vowel.
let vowelStart (str: string) =
match str[0] with
| 'a' | 'e' | 'i' | 'o' | 'u' -> printfn $"{str}"
| _ -> ()
// Demonstrate the use of delegates, including the Remove and
// Combine methods to create and modify delegate combinations.
[<EntryPoint>]
let main _ =
// Declare the StringContainer class and add some strings
let container = 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.
let conStart = CheckAndDisplayDelegate StringExtensions.conStart
let vowelStart = CheckAndDisplayDelegate StringExtensions.vowelStart
// Get the list of all delegates assigned to this MulticastDelegate instance.
let delegateList = conStart.GetInvocationList()
printfn $"conStart contains {delegateList.Length} delegate(s)."
let delegateList = vowelStart.GetInvocationList()
printfn $"vowelStart contains {delegateList.Length} delegate(s).\n"
// Determine whether the delegates are System.Multicast delegates.
if box conStart :? System.MulticastDelegate && box vowelStart :? System.MulticastDelegate then
printfn "conStart and vowelStart are derived from MulticastDelegate.\n"
// Execute the two delegates.
printfn "Executing the conStart delegate:"
container.DisplayAllQualified conStart
printfn "\nExecuting the vowelStart delegate:"
container.DisplayAllQualified vowelStart
printfn ""
// Create a new MulticastDelegate and call Combine to add two delegates.
let multipleDelegates =
Delegate.Combine(conStart, vowelStart) :?> CheckAndDisplayDelegate
// How many delegates does multipleDelegates contain?
let delegateList = multipleDelegates.GetInvocationList()
printfn $"\nmultipleDelegates contains {delegateList.Length} delegates.\n"
// Pass this multicast delegate to DisplayAllQualified.
printfn "Executing the multipleDelegate delegate."
container.DisplayAllQualified multipleDelegates
// Call remove and combine to change the contained delegates.
let multipleDelegates = Delegate.Remove(multipleDelegates, vowelStart) :?> CheckAndDisplayDelegate
let multipleDelegates = Delegate.Combine(multipleDelegates, conStart) :?> CheckAndDisplayDelegate
// Pass multipleDelegates to DisplayAllQualified again.
printfn "\nExecuting the multipleDelegate delegate with two conStart delegates:"
printfn $"{multipleDelegates}"
0
// 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
Remarques
MulticastDelegate est une classe spéciale. Les compilateurs et d’autres outils peuvent dériver de cette classe, mais vous ne pouvez pas en dériver explicitement. Il en va de même pour la classe Delegate.
Outre les méthodes qui délèguent les types héritent de MulticastDelegate, le Common Language Runtime fournit deux méthodes spéciales : BeginInvoke
et EndInvoke
. Pour plus d’informations sur ces méthodes, consultez Appel asynchrone de méthodes synchrones.
Une MulticastDelegate a une liste liée de délégués, appelée liste d’appel, composée d’un ou de plusieurs éléments. Lorsqu’un délégué de multidiffusion est appelé, les délégués de la liste d’appel sont appelés de façon synchrone dans l’ordre dans lequel ils apparaissent. Si une erreur se produit pendant l’exécution de la liste, une exception est levée.
Constructeurs
MulticastDelegate(Object, String) |
Initialise une nouvelle instance de la classe MulticastDelegate. |
MulticastDelegate(Type, String) |
Initialise une nouvelle instance de la classe MulticastDelegate. |
Propriétés
HasSingleTarget |
Obtient une valeur qui indique si le Delegate a une cible d’appel unique. (Hérité de Delegate) |
Method |
Obtient la méthode représentée par le délégué. (Hérité de Delegate) |
Target |
Obtient l’instance de classe sur laquelle le délégué actuel appelle la méthode d’instance. (Hérité de Delegate) |
Méthodes
Clone() |
Crée une copie superficielle du délégué. (Hérité de Delegate) |
CombineImpl(Delegate) |
Combine cette Delegate avec la Delegate spécifiée pour former un nouveau délégué. |
CombineImpl(Delegate) |
Concatène les listes d’appel du délégué de multidiffusion (combinable) spécifié et du délégué multidiffusion actuel (combinable). (Hérité de Delegate) |
DynamicInvoke(Object[]) |
Appelle dynamiquement (liaison tardive) la méthode représentée par le délégué actuel. (Hérité de Delegate) |
DynamicInvokeImpl(Object[]) |
Traite la liste d’appel complète. |
DynamicInvokeImpl(Object[]) |
Appelle dynamiquement (liaison tardive) la méthode représentée par le délégué actuel. (Hérité de Delegate) |
Equals(Object) |
Détermine si ce délégué de multidiffusion et l’objet spécifié sont égaux. |
GetHashCode() |
Retourne le code de hachage pour cette instance. |
GetInvocationList() |
Retourne la liste d’appel de ce délégué multidiffusion, dans l’ordre d’appel. |
GetMethodImpl() |
Retourne une méthode représentée par la MulticastDelegateactuelle. |
GetMethodImpl() |
Obtient la méthode représentée par le délégué actuel. (Hérité de Delegate) |
GetObjectData(SerializationInfo, StreamingContext) |
Obsolète.
Remplit un objet SerializationInfo avec toutes les données nécessaires pour sérialiser cette instance. |
GetObjectData(SerializationInfo, StreamingContext) |
Obsolète.
Non pris en charge. (Hérité de Delegate) |
GetType() |
Obtient la Type de l’instance actuelle. (Hérité de Object) |
MemberwiseClone() |
Crée une copie superficielle du Objectactuel. (Hérité de Object) |
RemoveImpl(Delegate) |
Supprime un élément de la liste d’appel de cette MulticastDelegate égale au délégué spécifié. |
RemoveImpl(Delegate) |
Supprime la liste d’appel d’un délégué de la liste d’appel d’un autre délégué. (Hérité de Delegate) |
ToString() |
Retourne une chaîne qui représente l’objet actuel. (Hérité de Object) |
Opérateurs
Equality(MulticastDelegate, MulticastDelegate) |
Détermine si deux objets MulticastDelegate sont égaux. |
Inequality(MulticastDelegate, MulticastDelegate) |
Détermine si deux objets MulticastDelegate ne sont pas égaux. |
Méthodes d’extension
GetMethodInfo(Delegate) |
Obtient un objet qui représente la méthode représentée par le délégué spécifié. |