作为方法参数的连接谓词的默认值[英] Default Value for Join Predicate as Method Parameter

本文是小编为大家收集整理的关于作为方法参数的连接谓词的默认值的处理/解决方法,可以参考本文帮助大家快速定位并解决问题,中文翻译不准确的可切换到English标签页查看源文。

问题描述

我有一个选择数据的方法.如果调用者可以提供一个谓词来修改 .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);
}

本文地址:https://www.itbaoku.cn/post/1557131.html

问题描述

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