FUNC<>获取参数信息 [英] Func<> getting the parameter info
本文介绍了FUNC<>获取参数信息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何让 Func键1所述的传递参数的值;>
LAMBDA在C#
How to get the value of the passed parameter of the Func<>
Lambda in C#
IEnumerable<AccountSummary> _data = await accountRepo.GetAsync();
string _query = "1011";
Accounts = _data.Filter(p => p.AccountNumber == _query);
这是我的扩展方法
and this is my extension method
public static ObservableCollection<T> Filter<T>(this IEnumerable<T> collection, Func<T, bool> predicate)
{
string _target = predicate.Target.ToString();
// i want to get the value of query here.. , i expect "1011"
throw new NotImplementedException();
}
我想获得的查询值里面分配到 _target
推荐答案
如果你想获得你将不得不参数过滤器扩展方法通过表情。通过传递一个FUNC你会通过编译拉姆达,所以你不能访问表达式树了。
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的
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
这篇关于FUNC<>获取参数信息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文