如何将带输入参数且有返回值的方法设为类对象的属性?
解决带参有返回值方法作为Question类属性的问题
核心原因
你之前用的Action委托仅支持无参数、无返回值的方法,带输入参数+有返回值的方法需要用Func系列委托来适配。
具体修改步骤
更新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; } }调用适配
现在可以直接把你的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
相关产品推荐
相关产品推荐

