簡體   English   中英

C#表達式樹綁定

[英]C# Expression Tree Binding

所以我想做的是使用表達式樹將謂詞應用於集合中的每個值(讀取映射或list.All(predicate))。 看來我沒有使輸入參數綁定到All提供的值的謂詞,而且我有些困惑。 這是我正在使用的代碼(使用linqpad):

public class SomeType
{
  public IEnumerable<bool> Collection { get; set; }
}

void Main()
{
  var list = new SomeType {
    Collection = new List<bool> { true, true, true }
  };
  var functor = Compiler((SomeType t) => t.Collection, (bool x) => x);
  functor(list).Dump();
}

MethodInfo FindMethod<TInput>(Type location, string name)
{
    var handle = location
        .GetMethods(BindingFlags.Static | BindingFlags.Public)
        .Where(method => method.Name == name).First();

    return handle.MakeGenericMethod(typeof(TInput));
}

Predicate<TObject> Compiler<TObject, TProperty>(
    Expression<Func<TObject, IEnumerable<TProperty>>> selector, 
    Expression<Predicate<TProperty>> predicate)
{
    var query = FindMethod<TProperty>(typeof(Enumerable), "All");
    var expression = Expression.Call(query,
        new Expression[] {
            Expression.Invoke(selector, selector.Parameters),
            Expression.Lambda<Func<TProperty, bool>>(predicate.Body,
                        Expression.Parameter(typeof(TProperty))),
        });         

    return Expression.Lambda<Predicate<TObject>>(expression,
        selector.Parameters).Compile();
}

謝謝,很抱歉,如果在另一個問題中回答了這個問題(我花了一段時間)。

確實可以,但是我不得不將Predicate<TObject>更改為Func<TObject, bool> 如果您願意,我可以嘗試將其改回。

static Predicate<TObject> Compiler<TObject, TProperty>(
    Expression<Func<TObject, IEnumerable<TProperty>>> selector,
    Expression<Func<TProperty, bool>> predicate)
{
    var query = FindMethod<TProperty>(typeof(Enumerable), "All");
    var expression = Expression.Call(
        query,
        Expression.Invoke(selector, selector.Parameters), 
        predicate);

    return Expression
        .Lambda<Predicate<TObject>>(expression, selector.Parameters)
        .Compile();
}

5分鍾后...如果您真的想使用Predicate<TObject> ...

static Predicate<TObject> Compiler<TObject, TProperty>(
    Expression<Func<TObject, IEnumerable<TProperty>>> selector,
    Expression<Predicate<TProperty>> predicate)
{
    var query = FindMethod<TProperty>(typeof(Enumerable), "All");

    var predicateAsFunc = Expression.Lambda<Func<TProperty, bool>>(
        predicate.Body, 
        predicate.Parameters);

    var expression = Expression.Call(
        query,
        Expression.Invoke(selector, selector.Parameters), 
        predicateAsFunc);

    return Expression
        .Lambda<Predicate<TObject>>(expression, selector.Parameters)
        .Compile();
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM