Partager via


How to: Define and Use Delegates 

The following code example demonstrates how to define and use a delegate. The .NET Framework provides a number of delegates, so often it is not necessary to define new delegates.

The following code example defines a delegate called MyCallback. This new delegate requires that the event handling code (the function that is called as a result of firing the delegate) have a return type of void and takes a String reference.

In the main function, the MyCallback delegate is instantiated using a static method defined by SomeClass. The delegate then becomes an alternate method of calling this function, as demonstrated by sending the string "single" to the delegate object.

Next, additional instances of MyCallback are linked together and then executed with a single call to the delegate object.

Example

// use_delegate.cpp
// compile with: /clr
using namespace System;

ref class SomeClass
{
public:
   static void Func(String^ str)
   {
      Console::WriteLine("static SomeClass::Func - {0}", str);
   }
};

ref class OtherClass
{
public:
   OtherClass( Int32 n ) 
   {
      num = n;
   }

   void Method(String^ str) 
   {
      Console::WriteLine("OtherClass::Method - {0}, num = {1}", 
         str, num);
   }

   Int32 num;
};

delegate void MyCallback(String^ str);

int main( ) 
{
   MyCallback^ callback = gcnew MyCallback(SomeClass::Func);   
   callback("single"); 

   callback += gcnew MyCallback(SomeClass::Func);   

   OtherClass^ f = gcnew OtherClass(99);
   callback += gcnew MyCallback(f, &OtherClass::Method);

   f = gcnew OtherClass(100);
   callback += gcnew MyCallback(f, &OtherClass::Method);

   callback("chained");

   return 0;
}

Output

static SomeClass::Func - single
static SomeClass::Func - chained
static SomeClass::Func - chained
OtherClass::Method - chained, num = 99
OtherClass::Method - chained, num = 100

See Also

Reference

delegate