在C#中使用反射将func转换为谓词 [英] Convert func to predicate using reflection in C#

查看:80
本文介绍了在C#中使用反射将func转换为谓词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我基本上是在尝试,但是我不知道T会是什么,所以我正在使用反射树和表达式树来构建事物.

I'm basically trying to do this, but I don't know what T will be, so I'm building things up using Reflection and Expression trees.

// Input (I don't know about "Book")
Type itemType = typeof(Book);

// Actual Code
// Build up func p => p.AuthorName == "Jon Skeet"
ParameterExpression predParam = Expression.Parameter(itemType, "p");
Expression left = Expression.Field(predParam, itemType.GetField("AuthorName"));
Expression right = Expression.Constant("Jon Skeet", typeof(string));
Expression equality = Expression.Equal(left, right);
Delegate myDelegate = Expression.Lambda(equality, new ParameterExpression[] { predParam }).Compile(); // Not sure if I need this

// Build up predicate type (Predicate<Book>)
Type genericPredicateType = typeof(Predicate<>);
Type constructedPredicateType = genericPredicateType.MakeGenericType(new Type[] { itemType });

// I need an instance to use this predicate, right? (** This Fails **)
object predicateInstance = Activator.CreateInstance(constructedPredicateType, new object[] { myDelegate });

基本上,我有一个List<Book>,我正在尝试对其进行反思,并介绍了InvokeFind方法. Find方法需要一个Predicate<Book>而不是Func<Book, bool>,而我一直对此表示怀疑.

Basically, I have a List<Book>, which I'm trying to reflect on and Invoke its Find method. The Find method needs a Predicate<Book> instead of Func<Book, bool>, and I've been beating my head against this for a few hours.

这是错误跟踪的第一部分:

Here is the first part of the error trace:

System.MissingMethodException: Constructor on type 'System.Predicate`1[[MyProject.Book, MyProject, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]' not found.

推荐答案

幸运的是,只需将呼叫更改为Expression.Lambda:

Fortunately this is pretty easy to do, just by changing your call to Expression.Lambda:

Type predicateType = typeof(Predicate<>).MakeGenericType(itemType);
LambdaExpression lambda = Expression.Lambda(predicateType, equality, predParam);
Delegate compiled = lambda.Compile();

目前尚不清楚您需要如何处理结果,请注意...如果弱类型版本适合您,那应该没事.

It's not clear what you needed to do with the result, mind you... if the weakly-typed version is okay for you, that should be fine.

这篇关于在C#中使用反射将func转换为谓词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆