MulticastDelegate MulticastDelegate MulticastDelegate MulticastDelegate Class

定義

表示多重傳送的委派 (Delegate);也就是說,委派可以在它的引動過程清單中包含一個以上的項目。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
繼承
MulticastDelegateMulticastDelegateMulticastDelegateMulticastDelegate
屬性

範例

下列範例會定義類別, StringContainer其中包含字串的集合。The following example defines a class, StringContainer, which includes a collection of strings. 其中一個成員是CheckAndDisplayDelegate委派, 用來顯示儲存StringContainer在符合特定準則的物件中的字串。One of its members is the CheckAndDisplayDelegate delegate, which is used to display strings stored in a StringContainer object that satisfy particular criteria. 委派會採用單一字串做為參數, 並void傳回 (或在 Visual Basic 中, 它是一個Sub程式)。The delegate takes a single string as a parameter and returns void (or, in Visual Basic, it's a Sub procedure). 它也包含一個方法, DisplayAllQualified其具有單一參數, 也就是CheckAndDisplayDelegate委派。It also includes a method, DisplayAllQualified, that has a single parameter, a CheckAndDisplayDelegate delegate. 這可讓您呼叫方法, 並根據委派包含的方法來顯示篩選出的一組字串。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.

此範例也會定義公用程式類別StringExtensions, 其中有兩個方法:The example also defines a utility class, StringExtensions, that has two methods:

  • ConStart, 顯示以輔音開頭的字串。ConStart, which displays strings that begin with a consonant.

  • VowelStart, 顯示以母音開頭的字串。VowelStart, which displays strings that begin with a vowel.

請注意, 這兩種方法都包含單一字串void參數, 並傳回。Note that both methods include a single string parameter and return void. 換句話說, 這兩種方法都可以指派給CheckAndDisplayDelegate委派。In other words, both methods can be assigned to the CheckAndDisplayDelegate delegate.

Test.Main方法是應用程式進入點。The Test.Main method is the application entry point. 它會將StringContainer物件具現化, 並以字串填入, CheckAndDisplayDelegate並建立兩vowelStart個委派, conStart也就是叫用單一方法的。It instantiates a StringContainer object, populates it with strings, and creates two CheckAndDisplayDelegate delegates, conStart and vowelStart, that invoke a single method. 然後, 它會Delegate.Combine呼叫方法來multipleDelegates建立委派ConStart , 這一開始會包含VowelStart和委派。It then calls the Delegate.Combine method to create the multipleDelegates delegate, which initially contains the ConStart and VowelStart delegates. 請注意, 叫multipleDelegates用委派時, 會以原始順序顯示集合中的所有字串。Note that when the multipleDelegates delegate is invoked, it displays all the strings in the collection in their original order. 這是因為每個字母會分別傳遞給每個委派, 而每個字母只符合兩個委派其中一個的篩選準則。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. 最後, 在Delegate.Remove呼叫和Delegate.Combine之後, multipleDelegates會包含conStart兩個委派。Finally, after calls to Delegate.Remove and Delegate.Combine, multipleDelegates contains two conStart delegates. 叫用時, 物件中的StringContainer每個字串都會顯示兩次。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

備註

MulticastDelegate是特殊的類別。MulticastDelegate is a special class. 編譯器和其他工具可以衍生自這個類別, 但是您無法明確地從中衍生。Compilers and other tools can derive from this class, but you cannot derive from it explicitly. Delegate類別也是如此。The same is true of the Delegate class.

除了委派型別繼承自MulticastDelegate的方法之外, common language runtime 也提供兩種特殊方法: BeginInvoke和。 EndInvokeIn addition to the methods that delegate types inherit from MulticastDelegate, the common language runtime provides two special methods: BeginInvoke and EndInvoke. 如需這些方法的詳細資訊, 請參閱以非同步方式呼叫同步方法For more information about these methods, see Calling Synchronous Methods Asynchronously.

MulticastDelegate具有委派的連結清單, 稱為調用清單, 由一個或多個專案組成。A MulticastDelegate has a linked list of delegates, called an invocation list, consisting of one or more elements. 叫用多播委派時, 會依其出現的順序, 以同步方式呼叫調用清單中的委派。When a multicast delegate is invoked, the delegates in the invocation list are called synchronously in the order in which they appear. 如果在執行清單期間發生錯誤, 則會擲回例外狀況。If an error occurs during execution of the list then an exception is thrown.

建構函式

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

初始化 MulticastDelegate 類別的新執行個體。Initializes a new instance of the MulticastDelegate class.

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

初始化 MulticastDelegate 類別的新執行個體。Initializes a new instance of the MulticastDelegate class.

方法

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

建立委派的淺層複本 (Shallow Copy)。Creates a shallow copy of the delegate.

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

結合這個 Delegate 和指定的 Delegate,形成新的委派。Combines this Delegate with the specified Delegate to form a new delegate.

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

動態叫用 (晚期繫結) 目前委派所表示的方法。Dynamically invokes (late-bound) the method represented by the current delegate.

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

處理完整的引動過程清單。Processes the full invocation list.

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

判斷這個多重傳送委派和指定的物件是否相等。Determines whether this multicast delegate and the specified object are equal.

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

傳回這個執行個體的雜湊碼。Returns the hash code for this instance.

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

依照引動過程的順序,傳回這個多重傳送委派的引動過程清單。Returns the invocation list of this multicast delegate, in invocation order.

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

傳回目前 MulticastDelegate 所表示的靜態方法。Returns a static method represented by the current MulticastDelegate.

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

使用所有序列化這個執行個體所需的資料,填入 SerializationInfo 物件。Populates a SerializationInfo object with all the data needed to serialize this instance.

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

取得目前執行個體的 TypeGets the Type of the current instance.

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

建立目前 Object 的淺層複本 (Shallow Copy)。Creates a shallow copy of the current Object.

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

從這個 MulticastDelegate 的引動過程清單中,移除和指定委派相等的項目。Removes an element from the invocation list of this MulticastDelegate that is equal to the specified delegate.

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

傳回代表目前物件的字串。Returns a string that represents the current object.

(Inherited from Object)

運算子

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

判斷兩個 MulticastDelegate 物件是否相等。Determines whether two MulticastDelegate objects are equal.

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

判斷兩個 MulticastDelegate 物件是否不相等。Determines whether two MulticastDelegate objects are not equal.

屬性

Method Method Method Method

取得委派所表示的方法。Gets the method represented by the delegate.

(Inherited from Delegate)
Target Target Target Target

取得目前的委派用來叫用執行個體方法的類別執行個體。Gets the class instance on which the current delegate invokes the instance method.

(Inherited from Delegate)

擴充方法

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

取得表示特定委派所代表之方法的物件。Gets an object that represents the method represented by the specified delegate.

適用於