🎉 Celebrating 25 Years of GameDev.net! 🎉

Not many can claim 25 years on the Internet! Join us in celebrating this milestone. Learn more about our history, and thank you for being a part of our community!

Delegates as reference objects.

Published January 08, 2007
Advertisement
This might be a little obvious to some who have used .NET or more exotic languages more than I, but I'd like to share anyways...

As part of Moe I had a setup where delegates were chained. A unit would have say... a "died" event. The tile would have a "unit died" event for any unit which died in that tile. The map would have a "unit died" event for any unit death on the map, and so on all the way up to the game.

This was all hardcoded, well sort of hardcoded... I actually used an abstract baseclass which was inherited up the path, adding more and more events. A little clever, but one of those things that is perhaps overly clever. For whatever reason I was thinking about this today on the drive home and realized that I am an idiot (again).

".NET delegates can be added to each other, can't they?" And if not it shouldn't be too hard to do something icky to make a wrapper class or bind some internal function to it.

Alas, it is not that easy. Delegates can be added together, but act as value types. delegate += delegate will copy the delegate's invocation list into the other. Cool, but then the parent delegate won't pickup any changes. Kinda useless...

Hrm. Generics won't work... normal delegates are weird and with no common baseclass or interface it'll be a pain to get them working and then I'll need to use some weird and unintuitive interface to use them. A normal class would work, but then I'd have to copy it many times for each method signature I want to use.

Hrm, I wonder what signature the Invoke functions have... Invoke matches, let's use that! It should be a common entrypoint to running the InvocationList so if the List changes, it should pick those up... Nope. That too copies the InvocationList! [that is REALLY odd by the way]


This on the other hand does work:

    DelegateType a,b,c;    c += functionC;    b += functionB;    a += functionA;    b += delegate(){ c(); };    a += delegate(){ b(); };    a();    // A, B, C;    b -= functionB;    c += functionA;    a();    // A, C, A;


Nifty.
Previous Entry Grr....
Next Entry Le Update
0 likes 0 comments

Comments

Nobody has left a comment. You can be the first!
You must log in to join the conversation.
Don't have a GameDev.net account? Sign up!
Profile
Author
Advertisement
Advertisement