如何解决通过反射传递Func <T,bool>作为参数?
我有一种方法:
public bool DoStuff<T>(T obj) {
// Do Stuff
return result;
}
我需要将它作为Func
public int Any(Func<int,bool> arg) {
}
或
public int Any(Func<string,bool> arg) {
}
所以我正在调用这种方法:
return instance.GetType().InvokeMember(method.Name,BindingFlags.InvokeMethod,null,instance,args);
我不知道如何将对DoStuff的引用包装为Func
如果有帮助,我正在写一种简单语言的解释器。 DoStuff将使用简单语言解释lambda表达式,并且调用的方法将是解释器的使用者提供的.NET函数。
更新
在跟随Hans评论中提供的链接(谢谢!)之后,我实现了以下内容:
Type delegateType = typeof(Func<,>).MakeGenericType(new []{argType,typeof(bool)});
MethodInfo delegatedMethod = this.GetType().GetMethod(nameof(DoStuff),BindingFlags.InvokeMethod | BindingFlags.Public | BindingFlags.Instance);
MethodInfo generic = delegatedMethod.MakeGenericMethod(argType);
Delegate myDelegate = Delegate.CreateDelegate(delegateType,this,generic);
var args = new object[] { myDelegate };
return instance.GetType().InvokeMember(method.Name,args);
但是InvokeMember调用给了我 System.MissingMethodException:'找不到方法'MyDomain.Any'。'
当我在Visual Studio中检查 myDelegate 变量时,它显示:
myDelegate = {Method = {Boolean DoStuff[Func`2](System.Func`2[System.Int32,System.Boolean])}
这是 args 数组中的唯一元素,我要调用的方法签名是:
public int Any(Func<int,bool> arg)
实例是包含Any方法的类的实例,而方法是Any方法的MethodInfo。
解决方法
所以这是一些有效的代码:
public class AnyImplementer
{
public int Any(Func<int,bool> func)
{
return func(10)? 1: 0;
}
}
public class DoStuffer
{
public bool DoStuff<T>(T obj)
{
return obj.ToString() != string.Empty;
}
public int a(Type argType,AnyImplementer anyImplementer)
{
Type delegateType = typeof(Func<,>).MakeGenericType(new[] { argType,typeof(bool) });
MethodInfo delegatedMethod = this.GetType().GetMethod(nameof(DoStuff),BindingFlags.InvokeMethod | BindingFlags.Public | BindingFlags.Instance);
MethodInfo generic = delegatedMethod.MakeGenericMethod(argType);
Delegate myDelegate = Delegate.CreateDelegate(delegateType,this,generic);
var args = new object[] { myDelegate };
return (int)anyImplementer.GetType().InvokeMember("Any",BindingFlags.InvokeMethod,null,anyImplementer,args);
}
}
public class Program
{
public static void Main(string[] args)
{
DoStuffer DoStuffer = new DoStuffer();
AnyImplementer anyImplementer = new AnyImplementer();
Console.WriteLine(DoStuffer.a(typeof(int),anyImplementer));
}
}
也可以在以下位置访问 https://pastebin.com/raw/3UxN6Sn4- 这个想法(基于OP的更新和相关问题)是使用由泛型方法组的方法信息构造的委托来创建将方法实例包装到对象中的。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。