[英]C# Reflection return method content as Delegate
I am working on an ability system that has pre written functions in the Abilities class and handles also Runtime methods, so I use delegates for lambda expression as well. 我正在一个具有Abilities类中预先编写的功能并且还处理运行时方法的功能系统上,因此我也将委托用于lambda表达式。 Obviously I need to call the pre written methods using Reflection. 显然,我需要使用反射调用预写方法。
I use a delegate that wraps a method: 我使用包装方法的委托:
public delegate void AbilityAction();
The Abilities class contains all the Ability-Methods. Abilities类包含所有Ability-Methods。
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 errors: 我已尽力而为,但它给了我错误:
this 这个
A constraint cannot be special class `System.Delegate' 约束不能是特殊类“ 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);
}
Thanks in advance. 提前致谢。
I can't see what you're actually trying to do without the delegate type and example method, but ... reading between the lines as best as I can, here's a similar example that works: 如果没有委托类型和示例方法,我看不到您实际上要做什么,但是...尽我所能地在两行之间阅读,这是一个类似的示例:
using System;
using System.Reflection;
class Foo
{
public int Bar(string whatever) => whatever.Length;
}
delegate int AbilityAction(string name);
static class Program
{
static void Main(string[] args)
{
var foo = new Foo();
var action = GetMethodInClass<AbilityAction>(nameof(foo.Bar), foo);
int x = action("abc");
Console.WriteLine(x); // 3
}
public static D GetMethodInClass<D>(string methodName, object target) where D : Delegate
{
var mi = target.GetType().GetMethod(methodName,
BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
return (D)Delegate.CreateDelegate(typeof(D), target, mi);
}
}
Note: if you don't have C# 7.3, the method needs some minor tweaks: 注意:如果您没有C#7.3,则该方法需要进行一些细微调整:
public static D GetMethodInClass<D>(string methodName, object target) where D : class
{
var mi = target.GetType().GetMethod(methodName,
BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
return (D)(object)Delegate.CreateDelegate(typeof(D), target, mi);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.