简体   繁体   中英

Creating Actions via reflection with type parameters to proxy call

Given a simple object

public class Foo {
   public void RunAction(Action<int, string, byte> action) {
        Action(0, null, 0);
   }
}

And given a sample pseudo-code method that reads this class to obtain the action type via reflection:

public void DoProxy(object [] calledWithParameters) {
     ... some code ...
}

public void DoReflection(Foo foo) {
   var actionParameterInfo = foo.getType().getMethod("RunAction").GetParameters()[0];
   var parameterTypes = actionParameterInfo.ParameterType.GenericTypeArguments;
   // Now I have the action type and the Type[] of the necessary parameters.
}

In this case how could I create dynamically an Action that calls my DoProxy with the received parameters on call?

You need a code which convert action parameters to an array before passing to a proxy. The easiest way is to use set of generic functions with different number of generic arguments:

public static class ProxyCaller
{
    public static Action<T1> CallProxy<T1>(Action<object[]> proxy) => new Action<T1>((T1 a1) => proxy(new object[] { a1 }));
    public static Action<T1, T2> CallProxy<T1, T2>(Action<object[]> proxy) => new Action<T1, T2>((T1 a1, T2 a2) => proxy(new object[] { a1, a2 }));
    public static Action<T1, T2, T3> CallProxy<T1, T2, T3>(Action<object[]> proxy) => new Action<T1, T2, T3>((T1 a1, T2 a2, T3 a3) => proxy(new object[] { a1, a2, a3 }));
    // More of these if number of arguments can be 4, 5 etc.

    public static object CreateAction(Action<object[]> proxy, Type[] parameterTypes)
    {
        var genericMethod = typeof(ProxyCaller).GetMethods().Where(m => m.Name == nameof(ProxyCaller.CallProxy) && m.GetGenericArguments().Length == parameterTypes.Length).First();
        var method = genericMethod.MakeGenericMethod(parameterTypes);
        var action = method.Invoke(null, new object[] { proxy });
        return action;
    }
}

and then in DoReflection():

var parameterTypes = actionParameterInfo.ParameterType.GenericTypeArguments;
var action = ProxyCaller.CreateAction(DoProxy, parameterTypes);
// action has type Action<int, string, byte> here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM