mardi 31 juillet 2018

C# Reflection return method content as Delegate

I would like to call functions using Reflection

I want to make the following section static:

var mi = Abilities.instance.GetType ().GetMethod (abilities[i].name, BindingFlags.Instance | BindingFlags.NonPublic) as MethodInfo; 

AbilityAction code = (AbilityAction)Delegate.CreateDelegate(typeof(AbilityAction), this, mi);

And then call it:

AbilityAction code = GetMethodInClass(abilities[i].name /*e.g. MegaJump*/, Abilities, AbilityAction);

I have tried my best but it gives me alot of errors:

public static Delegate GetMethodInClass<T, D>(string methodName, T sourceClass, D delegateType) where D : Delegate {
    var mi = sourceClass.GetType().GetMethod (methodName, BindingFlags.Instance | BindingFlags.NonPublic) as MethodInfo;    
    return (D)Delegate.CreateDelegate(typeof(delegateType), this, mi);
}

Thanks in advance.





Aucun commentaire:

Enregistrer un commentaire