Converter func em predicado usando reflexão em C #
Eu estou basicamente tentando fazeresta, mas não sei o que T será, então estou construindo coisas usando as árvores de reflexão e expressão.
// 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 });
Basicamente, eu tenho umList<Book>
, que estou tentando refletir eInvoke
EstáFind
método. oFind
método precisa de umPredicate<Book>
ao invés deFunc<Book, bool>
, e eu tenho batido minha cabeça contra isso por algumas horas.
Edit: Aqui está a primeira parte do rastreamento de erro:
System.MissingMethodException: Constructor on type 'System.Predicate`1[[MyProject.Book, MyProject, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]' not found.