开发者

differences between bound and unbound delegates in CLI/C++

开发者 https://www.devze.com 2023-04-03 02:58 出处:网络
Whats the difference between bound and unbound delegates? heres 开发者_如何学Gohow you create delegates of both types:

Whats the difference between bound and unbound delegates?

heres 开发者_如何学Gohow you create delegates of both types:

// bound delegate declaration
public delegate void Handler(int value);
// create a bound delegate
Handler^ handler = gcnew Handler(HandlerClass::Fun1);

// unbound delegate declaration
public delegate void UBHandler(ThisClass^, int value); 
// create an unbound delegate
UBHandler^ ubh = gcnew UBHandler(&ThisClass::Sum); 

these are nearly the same. then, you can create constructors for bound delegates that consist of two parameters:

HandlerClass^ obj = gcnew HandlerClass;
Handler^ handler2 = gcnew Handler (obj, & HandlerClass::Fun3);

it means that you can use this particular delegate to invoke a function that is not static (is an instance). but then you can do the same with unbound delegates. Here’s how you might call the ubh delegate:

ThisClass^ obj = gcnew ThisClass(99.0);
ubh(obj, 5);

so whats the point of having both types?

// code for HandlerClass
public ref class HandlerClass
{
  public:

  static void Fun1(int m)
  { Console::WriteLine(L”Function1 called with value {0}”, m); }
  static void Fun2(int m)
  { Console::WriteLine(L”Function2 called with value {0}”, m); }
  void Fun3(int m)
  { Console::WriteLine(L”Function3 called with value {0}”, m+value); }
  void Fun4(int m)
  { Console::WriteLine(L”Function4 called with value {0}”, m+value); }

  HandlerClass():value(1){}
  HandlerClass(int m):value(m){}

  protected:

  int value;
};


The difference is the exact time the target object value is generated. With a bound delegate it is generated when you create the delegate object and it is forever unchanging after that. An unbound delegate doesn't store the object reference, it is generated at the time the delegate is invoked. The same delegate can then be used to invoke the target method with different objects.

Unbound delegates are a match with the syntax of C++ member function pointers. There is no direct equivalent for bound delegates in C++.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号