[C#] Delegate adaptors and/or parameter binding

Started by
1 comment, last by Telastyn 18 years, 4 months ago
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:

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();
    }
}

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.
Advertisement
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();    }}
--AnkhSVN - A Visual Studio .NET Addin for the Subversion version control system.[Project site] [IRC channel] [Blog]
hrm. Yes, that does seem to be the little tidbit that would allow that use. If I used lamdbas more [or if this book spent more than a page on them] that would've been more evident.

Thanks a ton!

This topic is closed to new replies.

Advertisement