Jon*_*ock 5 c# reflection predicate expression-trees
基本上,我试图做这个,但我不知道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 });
Run Code Online (Sandbox Code Playgroud)
基本上,我有一个List<Book>,我试图反思和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.
Run Code Online (Sandbox Code Playgroud)
幸运的是,这很容易做到,只需将您的调用更改为Expression.Lambda:
Type predicateType = typeof(Predicate<>).MakeGenericType(itemType);
LambdaExpression lambda = Expression.Lambda(predicateType, equality, predParam);
Delegate compiled = lambda.Compile();
Run Code Online (Sandbox Code Playgroud)
目前尚不清楚您需要对结果做什么,请注意...如果弱类型版本适合您,那应该没问题。