我基本上試圖做this,但我不知道T是什麼,所以我使用反射和表達式樹來構建事物。將func轉換爲在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 });
基本上,我有一個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.
如果有人需要看到我調用查找方法的一部分,我也可以提供,但我認爲它會在必要的減損問題的一部分。 – 2010-08-16 16:44:20