Generic method with delegate type [duplicate]
My objective is demostrated with the following code:
void MyMethod<T>(T aMethod, params object[] aParams) where T: System.Delegate
{
aMethod.Invoke(aParams);
}
How can I do this kind of thing?
You could use Unconstrained Melody - or pinch the bit which allows this.
On the other hand, that's not actually going to expose an Invoke
method anyway. What do you want to do which can't be done with:
void MyMethod(Delegate aMethod, params object[] aParams)
{
aMethod.DynamicInvoke(aParams);
}
? I mean, you wouldn't actually have compile-time safety even with the generic version, as the parameters could be of the wrong types etc.
I'm not sure what you're actually trying to accomplish: Since only the compiler or runtime can inherit from System.Delegate, what point does the generic have over:
void MyMethod<T>(System.Delegate aMethod, params object[] aParams)
{
aMethod.DynamicInvoke(aParams);
}
Now, if you're trying to do something tricky with delegate type constraints, you can look at http://code.google.com/p/unconstrained-melody/ , which does some il rewriting to allow you to do it.
Or, just use an Action<object[]>
- or lots of overloads with Action<T>
, Action<T1,T2>
, etc.
void MyMethod(Action<object[]> aMethod, params object[] aParams)
{
aMethod(aParams);
}
//or
void MyMethod<T>(Action<T> aMethod, T param)
{
aMethod(param);
}
void MyMethod<T1, T2>(Action<T1, T2> aMethod, T1 param1, T2 param2)
{
aMethod(param1, param2);
}
I don't really like the huge list of overloads, but in some cases they provide the best library usability.
T
must be a type, but you don't need any generics
void MyMethod(Action<object[]> aMethod, params object[] aParams)
{
aMethod(aParams);
}
void Print(params object[] output)
{
foreach (var o in output)
Console.WriteLine(o);
}
call it like this:
MyMethod(Print, 1, "Hello");
精彩评论