How do I implement the Signals (from Django) concept in C# -
i'm trying implement signals django (http://docs.djangoproject.com/en/dev/topics/signals/), or concept in c# reduce/eliminate coupling/method dependencies.
so far, i'm replicating code fine, until point whereby realised methods ain't objects in c# in python. thought of pointers, , realised can't have pointers methods. c# version of delegates.
then realised delegates have unique signature it, can't mix delegated methods (with diff signatures) list, or can i?
i did bit more googling, , found reactive linq, far, linq looks awesome, still don't when use them.
so question is, how implement signals concept in c#? thanks!
oh did mention i'm new (1 day old) c#? have background of various other languages incl java/c/python.
cheers :)
what talking here typically handled events in c#, example;
public class sometype { public event eventhandler someevent; protected virtual void onsomeevent() { eventhandler handler = someevent; if(handler!=null) handler(this,eventargs.empty); } public void somethinginteresting() { // blah onsomeevent(); // notify subscribers // blap } // ... }
with subscribers...
sometype obj = new sometype(); //... obj.someevent += /* handler */ //...
the handler method, in discussion of signatures etc, common way of re-using existing methods non-matching signatures anonymous methods:
obj.someevent += delegate { this.text = "done!"; };
you can have list of delegates:
list<somedelegatetype> list = new list<somedelegatetype>(); list.add(...);
but might redundant because delegate instances multicast - can more directly:
action action = null; action += delegate { console.writeline("did a");}; action += delegate { console.writeline("did b");}; action(); // both & b
note more complex delegate usage might involv incoming argument values - example:
int = 24; func<int,int,int> func = (x,y) => (x * i) + y; int result = func(2, 3); // 51
by combining things anonymous methods (or lambdas, above) captured variables, issue of signatures having match issue - can wrap lambda make signature match (adding values or dropping arguments, required).
note events (in particular) common approach keep signature:
void somedelegatetype(object sender, someargstype args);
where someargstype : eventargs
- or use eventhandler<t>
you.
Comments
Post a Comment