Convierta func a predicado usando la reflexión en C #
Básicamente estoy tratando de haceresta, pero no sé qué será T, así que estoy construyendo cosas usando árboles de Reflexión y Expresión.
// 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 });
Básicamente, tengo unList<Book>
, que estoy tratando de reflexionar yInvoke
susFind
método. losFind
el método necesita unPredicate<Book>
en lugar deFunc<Book, bool>
, y he estado golpeándome la cabeza contra esto durante unas horas.
Editar: Aquí está la primera parte de la traza de error:
System.MissingMethodException: Constructor on type 'System.Predicate`1[[MyProject.Book, MyProject, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]' not found.