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

如何将带输入参数且有返回值的方法设为类对象的属性?

解决带参有返回值方法作为Question类属性的问题

核心原因

你之前用的Action委托仅支持无参数、无返回值的方法,带输入参数+有返回值的方法需要用Func系列委托来适配。

具体修改步骤

  1. 更新Question类的属性与构造函数
    将原来的Action类型替换为Func<List<Student>, List<Student>>(泛型参数对应你的方法输入和返回类型):

    public class Question
    {
        // 替换原Action属性为对应类型的Func
        public Func<List<Student>, List<Student>> Method { get; }
    
        // 构造函数参数同步改为Func类型
        public Question(Func<List<Student>, List<Student>> method)
        {
            Method = method;
        }
    }
    
  2. 调用适配
    现在可以直接把你的Question1方法传入Question的构造函数:

    // 创建Question实例
    var question = new Question(Question1);
    
    // 调用方法时传入参数并接收返回值
    List<Student> students = new List<Student>();
    List<Student> sortedStudents = question.Method(students);
    

扩展说明

如果以后需要不同参数/返回类型的方法,只需要调整Func的泛型参数即可:

  • 比如输入int、返回bool的方法,用Func<int, bool>
  • 多参数的话,比如输入string和int、返回List<Student>,用Func<string, int, List<Student>>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 11:56:00