i have a similiar situation:
ref class Manager
{
delegate void answer1(String^ Message, int Avalue);
delegate void answer2(Object^ Obj, double Something);
answer1 ^ Callbackfor1;
answer2 ^ Callbackfor2;
void RegisterCallback1(answer1 ^ Address);
void RegisterCallback2(answer2 ^ Address);
}
How can i manage that in a better solution? I had to create each time a delegate, a pointer and a procedure for each Callback. There is a better way to generalize? I think that delegate should be recreate each time, but i want avoid to recreate a procedure and a pointer.
First of all if you expose
Callbackfor1
andCallbackfor2
(I assume your class members are all public) then you don't also needRegisterCallback1
andRegisterCallback2
: they're just helper methods that make caller code even more prolix:Instead of:
However note that having your delegates public you're exposing them completely, caller may write this:
Then in my opinion you should remove that helper methods (keeping your fields public) or keep helper methods (making fields private). There is another option: event. They're exactly delegates but caller isn't allowed to set them (only add/remove a function in the call list):
Note that making them events (or keeping them private) also prevents callers to directly invoke them, you can raise events only from within class you declared them). Who uses your class:
About delegates declaration and signature: if you're target new .NET Framework versions you can use
Action
andFunc
generic delegates. Like this:That's all. Note that if you're instead targeting .NET Framework 2.0 where these delegates were not available then you can write it once and reuse them:
And use them as described before. Let's do a further step in the common .NET pattern of events. Let's create two classes (I don't know your domain so I pick random names):
Now change your
Manager
class:Usage is the same:
But method signature is different:
Inside your
Manager
class you'll raise an event like this (no need to check fornullptr
and to make it thread-safe, C++/CLI generates right code for you, note that this happens because ofevent
keyword regardless delegate signature). This code:Will become:
Is this better? Well to have a class makes your code little bit more prolix but it helps a lot when parameters change: you just need to add a property and recompile (with method parameters you'll need to find and update every method registerd as delegate for
Callback1
and add that parameter, even if unused).