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

如何为C#委托的过滤函数传入动态经验年限参数?

实现动态经验阈值的几种方案

方案1:利用闭包捕获外部变量(无需修改原有委托)

这种方法不用改动你已定义好的FilterDelegate和FilterAndDisplay方法,直接通过lambda表达式或嵌套方法捕获动态阈值,兼容性最强。

直接用lambda表达式传入

先定义动态阈值变量,再用lambda把它和员工对象的判断逻辑绑定:

// 动态设置阈值,可从用户输入、配置文件等渠道获取
int experienceThreshold = 4;

// 用lambda创建委托,自动捕获外部的experienceThreshold变量
Employee.FilterAndDisplay(employees, emp => emp.Experience < experienceThreshold);

封装成方法返回委托

如果想保留独立的逻辑方法,可写一个返回FilterDelegate的工厂方法,把阈值作为参数传入:

static FilterDelegate CreateCutOffFilter(int threshold)
{
    // threshold会被闭包捕获,后续调用委托时会使用该值
    return emp => emp.Experience < threshold;
}

// 调用时传入动态阈值
int targetThreshold = 3;
Employee.FilterAndDisplay(employees, CreateCutOffFilter(targetThreshold));

方案2:修改委托定义,直接包含阈值参数

如果愿意调整原有代码结构,可以让委托同时接收员工对象和阈值参数,对应修改FilterAndDisplay方法:

  1. 修改FilterDelegate定义:
public delegate bool FilterDelegate(Employee emp, int threshold);
  1. 更新Employee.FilterAndDisplay方法:
public static void FilterAndDisplay(List<Employee> employees, FilterDelegate filter, int threshold)
{
    var table = new ConsoleTable("ID", "Name", "Experience");

    foreach (var emp in employees)
    {
        if(filter(emp, threshold))
        {
            table.AddRow(emp.ID, emp.Name, emp.Experience);
        }
    }

    table.Write();
    Console.WriteLine(); 
}
  1. 调用时传入动态阈值:
int threshold = 4;
Employee.FilterAndDisplay(employees, (emp, thresh) => emp.Experience < thresh, threshold);

方案3:使用内置泛型委托替代自定义委托

C#内置了Func<T, TResult>系列泛型委托,可直接用Func<Employee, int, bool>替代自定义的FilterDelegate,省去额外的委托定义:

  1. 修改FilterAndDisplay方法:
public static void FilterAndDisplay(List<Employee> employees, Func<Employee, int, bool> filter, int threshold)
{
    var table = new ConsoleTable("ID", "Name", "Experience");

    foreach (var emp in employees)
    {
        if(filter(emp, threshold))
        {
            table.AddRow(emp.ID, emp.Name, emp.Experience);
        }
    }

    table.Write();
    Console.WriteLine(); 
}
  1. 调用时传入动态阈值:
int threshold = 2;
Employee.FilterAndDisplay(employees, (emp, thresh) => emp.Experience < thresh, threshold);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 11:03:19