Convert-Funktion zum Prädizieren mit Reflektion in C #
Ich versuche im Grunde zu tunDie, aber ich weiß nicht, was T sein wird, also baue ich Dinge mit Reflection- und Expression-Bäumen auf.
// 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 });
rundsätzlich habe ich einList<Book>
, über das ich nachdenken möchte undInvoke
es istFind
Methode. DasFind
Methode braucht einPredicate<Book>
Anstatt vonFunc<Book, bool>
, und ich habe ein paar Stunden lang meinen Kopf dagegen geschlagen.
Bearbeiten: Hier ist der erste Teil des Fehlerprotokolls:
System.MissingMethodException: Constructor on type 'System.Predicate`1[[MyProject.Book, MyProject, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]' not found.