连接谓词作为方法参数的默认值

连接谓词作为方法参数的默认值

本文介绍了连接谓词作为方法参数的默认值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个选择数据的方法.如果调用方可以提供谓词来修改.Where(),则它可以支持多种用例.我尝试了类似的

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.
}

到目前为止效果很好.

但是,某些用例不需要提供任何过滤器(实际版本具有其他参数来区分每个用例的行为).我认为为filter参数提供默认值会很方便

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)

但是,这不能编译.该错误指出NoFilter必须是编译时常量.

However, that does not compile. The error states that NoFilter must be a compile-time constant.

是否可以在GetData()中为filter提供默认值?

Is there a way to provide a default value for filter in GetData()?

推荐答案

提供默认值null并将其与方法内部的真实委托交换:

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);
}

这篇关于连接谓词作为方法参数的默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 06:17