如何将谓词作为参数C#传递 [英] How to pass a predicate as parameter c#
本文介绍了如何将谓词作为参数C#传递的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何在不传递谓词的情况下将谓词传递给方法,又如何使它起作用?我想也许是这样,但这似乎不正确。
How can I pass a predicate into a method but also have it work if no predicate is passed? I thought maybe something like this, but it doesn't seem to be correct.
private bool NoFilter() { return true; }
private List<thing> GetItems(Predicate<thing> filter = new Predicate<thing>(NoFilter))
{
return rawList.Where(filter).ToList();
}
推荐答案
private List<thing> GetItems(Func<thing, bool> filter = null)
{
return rawList.Where(filter ?? (s => true)).ToList();
}
在此表达式中 s => true
是后备过滤器,如果参数 filter
为空,则将对其求值。它只获取列表的每个条目(如 s
)并返回 true
。
In this expression s => true
is the fallback filter which is evaluated if the argument filter
is null. It just takes each entry of the list (as s
) and returns true
.
这篇关于如何将谓词作为参数C#传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文