开发者

Generic method with delegate type [duplicate]

开发者 https://www.devze.com 2023-01-29 14:13 出处:网络
This question already has answers here: C# Generics won't allow Delegate Type Constraints 开发者_StackOverflow(8 answers)
This question already has answers here: C# Generics won't allow Delegate Type Constraints 开发者_StackOverflow (8 answers) Closed 9 years ago.

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");
0

精彩评论

暂无评论...
验证码 换一张
取 消