Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have the following method signature:

public static void InvokeInFuture(Delegate method, 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.

like image 864
DxCK Avatar asked Dec 11 '09 20:12

DxCK


1 Answers

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;
}
like image 120
Steve Guidi Avatar answered Oct 21 '22 05:10

Steve Guidi