问题描述
我有一个选择数据的方法.如果调用者可以提供一个谓词来修改 .Where(),它可以支持多个用例.我尝试过类似
private class ABJoin { public A A { get; set; } public B B { get; set; } } bool NoFilter(ABJoin join, int index) { return true; // Don't filter at all for this } private IEnumerable<TResult> GetData (Func<ABJoin, int, bool> filter) { var query = ctx.TypeA .Join(ctx.TypeB, a => a.BId, b => b.Id, (a, b) => new ABJoin() { A = a, B = b }) // etc. }
到目前为止效果很好.
但是,有些用例不需要提供任何过滤器(实际版本有其他参数来区分每个用例的行为).我认为为过滤器参数提供默认值会很方便
private IEnumerable<TResult> GetData (Func<ABJoin, int, bool> filter = NoFilter)
但是,这不会编译.错误指出 NoFilter 必须是编译时常量.
有没有办法为 GetData() 中的 filter 提供默认值?
推荐答案
提供 null 的默认值,并在方法内将其与真正的委托交换:
private IEnumerable<TResult> GetData(Func<ABJoin, int, bool> filter = null) { filter = filter ?? ((a,b) => true); }
问题描述
I have a method that selects data. It can support multiple use cases if the caller can provide a predicate to modify the .Where(). I attempted something like
private class ABJoin { public A A { get; set; } public B B { get; set; } } bool NoFilter(ABJoin join, int index) { return true; // Don't filter at all for this } private IEnumerable<TResult> GetData (Func<ABJoin, int, bool> filter) { var query = ctx.TypeA .Join(ctx.TypeB, a => a.BId, b => b.Id, (a, b) => new ABJoin() { A = a, B = b }) // etc. }
Works great, so far.
However, some use cases do not need to provide any filter (the real version has other parameters to distinguish behavior per use case). I thought it would be handy to provide a default value for the filter parameter
private IEnumerable<TResult> GetData (Func<ABJoin, int, bool> filter = NoFilter)
However, that does not compile. The error states that NoFilter must be a compile-time constant.
Is there a way to provide a default value for filter in GetData()?
推荐答案
Provide default value of null and swap it with real delegate inside the method:
private IEnumerable<TResult> GetData(Func<ABJoin, int, bool> filter = null) { filter = filter ?? ((a,b) => true); }