c# - 在 C# 中使用反射将函数转换为谓词

标签 c# reflection expression-trees predicate

我基本上是在尝试做 this ,但我不知道 T 是什么,所以我正在使用反射树和表达式树构建东西。

// 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> ,我正在努力反射(reflection)和Invoke它的Find方法。 Find方法需要 Predicate<Book>而不是 Func<Book, bool> ,几个小时以来我一直在为此苦苦思索。

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

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

最佳答案

幸运的是,这很容易做到,只需将您的调用更改为 Expression.Lambda:

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

不清楚您需要对结果做什么,请注意...如果弱类型版本适合您,那应该没问题。

关于c# - 在 C# 中使用反射将函数转换为谓词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3495243/

相关文章:

c# - 查询以检索每个操作的最新状态

c# - 如何在 C# 代码后面的按钮中添加 StackPanel

c# - 正则表达式 - 比赛后只允许有空格或什么都没有

c# - Generics & Reflection - GenericArguments[0] 违反类型约束

java:传递一个对象并返回相同对象的类型

Java 泛型 - 类型转换问题

c# - 如何解析简单捕获的闭包表达式并获取目标对象和选择器

c# - 动态成员表达式

c# - 字符串表达式

c# - 带有 VSTO 的 Excel 中的表格