开发者

Checking whether an `object[] args` satisfies a Delegate instance?

I have the following method signature:

public static void InvokeInFuture(Delegate meth开发者_JAVA百科od, params object[] args)
{
    // ...
}

The delegate and the arguments are saved to a collection for future invoking.

Is there any way i can check whether the arguments array satisfies the delegate requirements without invoking it?

Thanks.

EDIT: Thanks for the reflection implementation, but i searching for a built-in way to do this. I don't want to reinvert the wheel, the .NET Framework already have this checking implemented inside Delegate.DynamicInvoke() somewhere, implementation that handles all those crazy special cases that only Microsoft's developers can think about, and passed Unit Testing and QA. Is there any way to use this built-in implementation?

Thanks.


You can use reflection to get the method signature of the delegate as follows.

using System;
using System.Reflection;

bool ValidateDelegate(Delegate method, params object[] args)
{
    ParameterInfo[] parameters = method.Method.GetParameters();
    if (parameters.Length != args.Length) { return false; }

    for (int i = 0; i < parameters.Length; ++i)
    {
        if (parameters[i].ParameterType.IsValueType && args[i] == null ||
            !parameters[i].ParameterType.IsAssignableFrom(args[i].GetType()))
        {
            return false;
        }
    }

    return true;
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜