[英]Convert func to predicate using reflection in C#
基本上,我試圖做這個 ,但我不知道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 });
基本上,我有一個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.
幸運的是,通過更改對Expression.Lambda
的調用,這很容易做到:
Type predicateType = typeof(Predicate<>).MakeGenericType(itemType);
LambdaExpression lambda = Expression.Lambda(predicateType, equality, predParam);
Delegate compiled = lambda.Compile();
目前還不清楚你需要對結果做些什么,請注意......如果弱類型版本對你沒問題,那應該沒問題。
不確定這是否與Jon的答案相同:
public static Predicate<T> GetPredicate<T>()
{
Type itemType = typeof(T);
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);
Func<T, bool> function = (Func<T, bool>)Expression.Lambda(equality, new[] { predParam }).Compile();
return new Predicate<T>(function);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.