Func<> getting the parameter info

佐手、 提交于 2019-12-05 05:17:44

If you want to get the parameter you will have to pass expression. By passing a "Func" you will pass the compiled lambda, so you cannot access the expression tree any more.

public static class FilterStatic
{
    // passing expression, accessing value
    public static IEnumerable<T> Filter<T>(this IEnumerable<T> collection, Expression<Func<T, bool>> predicate)
    {
        var binExpr = predicate.Body as BinaryExpression;
        var value = binExpr.Right;

        var func = predicate.Compile();
        return collection.Where(func);
    }

    // passing Func
    public static IEnumerable<T> Filter2<T>(this IEnumerable<T> collection, Func<T, bool> predicate)
    {
        return collection.Where(predicate);
    }
}

Testmethod

var accountList = new List<Account>
{
    new Account { Name = "Acc1" },
    new Account { Name = "Acc2" },
    new Account { Name = "Acc3" },
};
var result = accountList.Filter(p => p.Name == "Acc2");  // passing expression
var result2 = accountList.Filter2(p => p.Name == "Acc2");  // passing function

so instead of passing your predicate as a Func<T,bool> pass an Expression tree instead Expression<Func<T,bool>

You can then examine what type of expression it is and get it's component parts, it won't affect how the method is called, you can still pass it a lambda.

I don't really think you can do that. Check following situation:

Your predicate is set to be Func<T, bool> predicate, so you can call it like that:

Accounts = _data.Filter(p => true);

What would you like to get from that kind of call?

(p) => true satisfies Func<T, bool>, because it takes T as input and returns bool value.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!