class foo{
public delegate void foo_d();
public event foo_d bar;
public void trigger(){bar();}
}
class echo_str{
public static void echo(string str){
Console.WriteLine("{0}",str);
}
}
class Program{
static void Main(string[] args){
foo eventfoo=new foo();
// Adapt the void(string) to fit into a void()
eventfoo.bar+=bind(echo_str.echo,"moo.");
eventfoo.trigger();
}
}
[C#] Delegate adaptors and/or parameter binding
I recently picked up a book on C#, after being capable with C-style languages [C,C++], scripting languages [perl, unix shell], but not functional or Java style languages.
One of the neat things with the language is the first rate citizenship of delegates and events. One thing I noticed though that was missing was adapters for them.
Coming from C++, I am used to boost::function/bind to be able to adapt functions into certain signatures in a nice generic fashion.
In C#, I haven't yet found a nice simple way to do something like this:
So, am I just not searching well?
Did I miss something that makes this easy? [CreateDelegate doesn't do more than instance binding. Some of the reflection stuff sort of works, but someone already tried that, slowly]
Do I just need to wait for someone to do it?
Am I missing a good reason I should never have to do this?
The lack of operator() overloading, template black magic, and typed templates [template <int> class...] makes the usual methods... difficult.
I'd use an anonymous delegate (2.0 only):
class foo{ public delegate void foo_d(); public event foo_d bar; public void trigger(){bar();}}class echo_str{ public static void echo(string str){ Console.WriteLine("{0}",str); }}class Program{ static void Main(string[] args){ foo eventfoo=new foo(); // anonymous delegate here: eventfoo.bar+= delegate{ echo_str.echo("moo."); }; eventfoo.trigger(); }}
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement