In pratica sto provando a fare this, ma non so cosa sarà T, quindi sto costruendo le cose usando gli alberi di Reflection ed Expression.Converti func per predicate usando reflection in C#
// 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 });
Fondamentalmente, ho un List<Book>
, che sto cercando di riflettere e Invoke
suo metodo Find
. Il metodo Find
ha bisogno di un Predicate<Book>
invece di Func<Book, bool>
e ho battuto la testa contro questo per alcune ore.
Edit: Ecco la prima parte della Traccia di errore:
System.MissingMethodException: Constructor on type 'System.Predicate`1[[MyProject.Book, MyProject, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]' not found.
Se qualcuno ha bisogno di vedere la parte in cui invoco il metodo Find, posso fornire anche questo, ma ho pensato che sarebbe sminuire l'essenziale parte della domanda. –