Reputation: 85
So there is this class in gtk sharp:
http://docs.go-mono.com/?link=E%3aGtk.Button.Clicked
It accepts EventHandler type events. I want to use a custom event handler that passes strings to the function it calls.
The thing is, I don't seem to be able to feed it my CustomEventHandler. Even if I use EventHandler as an abstract class in its definition.
Why can't I do it? I think I am missing something obvious...
Edit, my code:
public MainWindow () : base (Gtk.WindowType.Toplevel)
{
Button button = new Button ("button");
button.Clicked += new EventHandler(my_function);
this.Add (button);
Build ();
}
static void my_function(object obj, EventArgs args){
//some code
}
I've tried changing new EventHandler to MyEventHandler(my_function, MyCustomArghs) but no matter what combination I try, there are always some errors. Mainly related to trying to cast to type EventHandler - event though MyEventHandler is a child of EventHandler class.
Upvotes: 1
Views: 303
Reputation: 70661
The event handler subscribed to the event must conform to C#'s delegate type rules. In particular, while you can "broaden" the arguments, you can't "narrow" them. I.e. your arguments can be base types of the actual delegate-specific argument types, but they cannot be derived classes of them.
You're not specific about what you would actually put in your custom EventArgs
class. But the usual way to approach this kind of scenario is to wrap your event handler method in an anonymous method that matches the delegate type, using the anonymous method as an adapter.
For example:
public MainWindow () : base (Gtk.WindowType.Toplevel)
{
Button button = new Button ("button");
button.Clicked += (sender, e) => my_function("some string literal");
this.Add (button);
Build ();
}
static void my_function(string text){
//some code
}
Note that when you take this approach, your actual event handler doesn't have to have anything like the actual event signature at all. You just have to be able to write whatever code is required to adapt the actual event arguments to those your handler will take. If you want to completely ignore the event's actual arguments and just pass something else, you can.
Upvotes: 1