I'm faced with a legacy API that doesn't use .NET events, but rather requires me to do this:
// (first arg is System.Object, second arg is string, myFoo is of type Foo)
myFoo.AddCallback(this, "DoSomething(int)");
This API requires that DoSomething
be an instance method on this
, and that it take an int.
Is there a way I can use force this API to be usable in a typesafe way?
More precisely: I want to write an extension method for Foo, which allows me to call AddCallback with a .NET delegate, rather than a receiver-signature pair. I'm imagining something like this:
// extension method definition
public static void AddCallback(this Foo foo, Action action)
{
foo.AddCallback(
FigureOutReceiverOf(action), // ?
FigureOutSignatureOf(action)); // ?
}
public static void AddCallback<T>(this Foo foo, Action<T> action)
{ ... } // and so on, for up to, say, 10 type-arguments
// usage:
myFoo.AddCallback(DoSomething)
// or even a lambda:
myFoo.AddCallback((i) => Console.WriteLine(i));
If it's possible to do this via an extension method hack, it would make my life better. Also I'm simply interested if it's possible given C#'s capabilities.
By the way, the legacy API is called qt4dotnet.