C#反射返回方法内容为委托

我正在开发一个能力系统,该系统在 Abilities 类中具有预先编写的函数并处理运行时方法,因此我也将委托用于 lambda 表达式。显然我需要使用反射调用预先编写的方法。


我使用包装方法的委托:


public delegate void AbilityAction();

Abilities 类包含所有的能力方法。


我想让以下部分静态:


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


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

然后调用它:


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

我已经尽力了,但它给了我错误:


这个


约束不能是特殊类“System.Delegate”


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);

}

提前致谢。


慕侠2389804
浏览 231回答 1
1回答

qq_花开花谢_0

如果没有委托类型和示例方法,我无法看到您实际尝试做什么,但是......尽我所能阅读行间,这里有一个类似的例子:using System;using System.Reflection;class Foo{&nbsp; &nbsp; public int Bar(string whatever) => whatever.Length;}delegate int AbilityAction(string name);static class Program{&nbsp; &nbsp; static void Main(string[] args)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; var foo = new Foo();&nbsp; &nbsp; &nbsp; &nbsp; var action = GetMethodInClass<AbilityAction>(nameof(foo.Bar), foo);&nbsp; &nbsp; &nbsp; &nbsp; int x = action("abc");&nbsp; &nbsp; &nbsp; &nbsp; Console.WriteLine(x); // 3&nbsp; &nbsp; }&nbsp; &nbsp; public static D GetMethodInClass<D>(string methodName, object target) where D : Delegate&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; var mi = target.GetType().GetMethod(methodName,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);&nbsp; &nbsp; &nbsp; &nbsp; return (D)Delegate.CreateDelegate(typeof(D), target, mi);&nbsp; &nbsp; }}注意:如果您没有 C# 7.3,该方法需要一些小的调整:&nbsp; &nbsp; public static D GetMethodInClass<D>(string methodName, object target) where D : class&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; var mi = target.GetType().GetMethod(methodName,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);&nbsp; &nbsp; &nbsp; &nbsp; return (D)(object)Delegate.CreateDelegate(typeof(D), target, mi);&nbsp; &nbsp; }
打开App,查看更多内容
随时随地看视频慕课网APP