如何在C#中对泛型列表动态执行Min、Max、Sum聚合函数?
问题原因
你遇到的问题是因为Enumerable.Sum和Min/Max的泛型方法签名不一致:
Min/Max存在接收两个泛型参数的重载(TSource和TResult),和你代码里传递的new Type[] { item.Type, selector.ReturnType }匹配;- 但
Sum接收Func<T, double>的重载只有一个泛型参数(TSource),因为返回值类型(double)已经由selector的返回类型确定,不需要额外指定第二个泛型参数。
你的代码统一给所有方法传递了两个泛型参数,导致Sum找不到匹配的重载,抛出异常。
修复方案
修改BuildFunc方法,动态根据方法名获取正确的方法重载,替代硬编码的泛型参数数量:
Func<IEnumerable<T>, double> BuildFunc<T>(string propertyName, string funcName) { var source = Expression.Parameter(typeof(IEnumerable<T>), "source"); var item = Expression.Parameter(typeof(T), "item"); Expression value = Expression.PropertyOrField(item, propertyName); var selector = Expression.Lambda<Func<T, double>>(value, item); MethodInfo targetMethod; if (funcName == "Sum") { // 查找Sum的正确重载:Sum<TSource>(IEnumerable<TSource>, Func<TSource, double>) targetMethod = typeof(Enumerable).GetMethod( funcName, new[] { typeof(IEnumerable<T>), selector.GetType() }) ?? throw new InvalidOperationException($"找不到{funcName}方法的匹配重载"); } else { // 查找Min/Max的双泛型参数重载:Min<TSource, TResult>(...) targetMethod = typeof(Enumerable).GetMethod( funcName, BindingFlags.Public | BindingFlags.Static, null, new[] { typeof(IEnumerable<T>), selector.GetType() }, null) ?? throw new InvalidOperationException($"找不到{funcName}方法的匹配重载"); targetMethod = targetMethod.MakeGenericMethod(typeof(T), typeof(double)); } var methodCall = Expression.Lambda<Func<IEnumerable<T>, double>>( Expression.Call(targetMethod, source, selector), source); return methodCall.Compile(); }
补充说明
如果需要支持更多聚合方法(比如Average),可以扩展判断逻辑,或者更通用地通过筛选方法的参数和泛型参数来匹配,而不是硬编码方法名。比如通过检查方法的泛型参数数量、参数类型是否匹配来自动适配。
内容的提问来源于stack exchange,提问作者Ankush Madankar
相关产品推荐
相关产品推荐

