I create a Delegate
from an method I know only takes one parameter and later call it using a DynamicInvoke
, but I was wondering if it was possible to get an Action
to invoke directly.
Here is what I have currently:
private IEnumerable<MethodInfo> GetMethods()
=> GetType().GetMethods(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
private IEnumerable<Thing> GetThings() {
foreach (var method in GetMethods()) {
var attribute = (MyAttribute) method.GetCustomAttribute(typeof(MyAttribute), false);
var theDelegate = CreateDelegate(method);
return new Thing(attribute.Name, theDelegate);
}
}
private Delegate CreateDelegate(MethodInfo method) {
Type requestType = method.GetParameters()[0].ParameterType,
actionType = typeof(Action<>).MakeGenericType(requestType);
return Delegate.CreateDelegate(actionType, this, method);
}
public void Invoke(Thing thing, string json) {
var requestType = MyDelegate.Method.GetParameters()[0].ParameterType;
var o = Deserialize(json, requestType);
thing.TheDelegate.DynamicInvoke(o);
}
Using an Action, not only would it be faster but it would look much neater. The following code doesn't work but there must be a way to get something similar:
private Action CreateAction(MethodInfo method) {
Type requestType = method.GetParameters()[0].ParameterType,
actionType = typeof(Action<>).MakeGenericType(requestType);
return (Action) Delegate.CreateDelegate(actionType, this, method);
}
public void Invoke(Thing thing, string json) {
Type requestType = MyAction.GetParameters()[0].ParameterType;
var o = Deserialize(json, requestType);
thing.MyAction(o);
}