You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

能否为Expression<Func<T,bool>>类型filter参数设置x => true的默认值?

报错原因

C# 语法要求方法的默认参数值必须是编译时常量,而 Lambda 表达式属于运行时创建的表达式树对象,不属于编译时常量,因此无法直接作为默认值使用。

正确实现方案

方案1:参数默认值设为 null,方法内部做判断

将 filter 参数的默认值设为 null,方法内部判断如果未传参就使用全量过滤条件,或者直接跳过 Where 过滤:

public static List<Test> getAll(Expression<Func<Test, bool>> filter = null)
{           
    var query = context.Test.FromSqlRaw($"Select * from {tableName}");
    if (filter != null)
    {
        query = query.Where(filter);
    }
    return query.ToList();
}

也可以直接给 null 的参数赋默认表达式:

public static List<Test> getAll(Expression<Func<Test, bool>> filter = null)
{           
    filter ??= x => true;
    return context.Test.FromSqlRaw($"Select * from {tableName}").Where(filter).ToList();
}

方案2:通过方法重载实现

写两个同名重载方法,分别适配带过滤参数和不带过滤参数的场景,逻辑更清晰:

// 无参数,返回全量数据
public static List<Test> getAll()
{           
    return context.Test.FromSqlRaw($"Select * from {tableName}").ToList();
}

// 带过滤参数,返回条件匹配的数据
public static List<Test> getAll(Expression<Func<Test, bool>> filter)
{           
    return context.Test.FromSqlRaw($"Select * from {tableName}").Where(filter).ToList();
}

内容的提问来源于stack exchange,提问作者B_Cbk

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.23 21:15:03