Export (0) Print
Expand All

__delegate

Visual Studio .NET 2003

Defines a reference type that can be used to encapsulate a method with a specific signature.

__delegate function-declarator

Remarks

A delegate is roughly equivalent to a C++ function pointer except for the following difference:

  • A delegate can only be bound to one or more methods within a __gc class.

When the compiler encounters the __delegate keyword, a definition of a __gc class is generated. This __gc class has the following characteristics:

  • It inherits from System::MulticastDelegate.
  • It has a constructor that takes two arguments: a pointer to a __gc class or NULL (in the case of binding to a static method) and a fully qualified method of the specified type.
  • It has a method called Invoke, whose signature matches the declared signature of the delegate.

For more information on delegates and their base implementations, see 9 Delegates.

Example

In the following example, a __gc class (MyCalendar) and a delegate (GetDayOfWeek) are declared. The delegate is then bound to the different methods of MyCalendar, invoking each in turn:

// keyword__delegate.cpp
// compile with: /clr
#using <mscorlib.dll>
using namespace System;

__delegate int GetDayOfWeek();
__gc class MyCalendar
{
public:
   MyCalendar() : m_nDayOfWeek(4) {}
   int MyGetDayOfWeek() { Console::WriteLine("handler"); return m_nDayOfWeek; }
   static int MyStaticGetDayOfWeek() { Console::WriteLine("static handler"); return 6; }
private:
   int m_nDayOfWeek;
};

int main ()
{
   GetDayOfWeek * pGetDayOfWeek;  // declare delegate type
   int nDayOfWeek;
   
   // bind delegate to static method
   pGetDayOfWeek = new GetDayOfWeek(0, &MyCalendar::MyStaticGetDayOfWeek);
   nDayOfWeek = pGetDayOfWeek->Invoke();
   Console::WriteLine(nDayOfWeek);

   // bind delegate to instance method
   MyCalendar * pcal = new MyCalendar();
   pGetDayOfWeek = static_cast<GetDayOfWeek*>(Delegate::Combine(pGetDayOfWeek,
      new GetDayOfWeek(pcal, &MyCalendar::MyGetDayOfWeek)));
   nDayOfWeek = pGetDayOfWeek->Invoke();
   Console::WriteLine(nDayOfWeek);

   // delegate now bound to two methods; remove instance method
   pGetDayOfWeek = static_cast<GetDayOfWeek*>(Delegate::Remove(pGetDayOfWeek,
      new GetDayOfWeek(pcal, &MyCalendar::MyGetDayOfWeek)));
   return 0;
}

Output

static handler
6
static handler
handler
4

See Also

Managed Extensions for C++ Reference | C++ Keywords

Show:
© 2014 Microsoft