为什么下面的不编译?
using System;
using System.Linq;
using System.Linq.Expressions;
public static class Extensions
{
public static V? SumOrDefault<T, V>(this IQueryable<T> @this, Expression<Func<T, V>> selector)
where V : struct, IComparable, IComparable<V>, IConvertible, IEquatable<V>, IFormattable
{
Expression<Func<T, V?>> nullableSelector = null; // omitted for brevity
return Queryable.Sum<T>(@this, nullableSelector);
}
}
它给出了此错误:
error CS1503: Argument 2: cannot convert from 'System.Linq.Expressions.Expression<System.Func<T, V?>>' to 'System.Linq.Expressions.Expression<System.Func<T, decimal>>'
两个问题:
- 为什么它尝试并失败地调用
Sum<>
的decimal
版本? - 为什么在
System.Linq.Queryable
中找不到该函数的decimal?
版本?
public static decimal? Sum<TSource>(this IQueryable<TSource> source, Expression<Func<TSource, decimal?>> selector);
如果这有效,从技术上讲,你可以用十进制无法转换但仍尊重你where
的东西来调用该SumOrDefault
函数(例如,自定义的"不可求和"类会(。string
而且它找不到函数的decimal?
版本,因为它不知道要安全地转换为哪种类型。
C# 没有办法将类型筛选为仅数字 AFAIK,因此您必须像 2001 年一样手动重载它们:
public static decimal? SumOrDefault<T>(this IQueryable<T> @this, Expression<Func<T, decimal>> selector)
public static double? SumOrDefault<T>(this IQueryable<T> @this, Expression<Func<T, double>> selector)
//etc.