我基本上是在尝试做 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/