[英]cannot convert from 'System.Linq.Expressions.Expression<System.Func<T, V?>>' to 'System.Linq.Expressions.Expression<System.Func<T, decimal>>'
Why doesn't the following compile?为什么以下不编译?
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);
}
}
It gives this error:它给出了这个错误:
error CS1503: Argument 2: cannot convert from 'System.Linq.Expressions.Expression<System.Func<T, V?>>' to 'System.Linq.Expressions.Expression<System.Func<T, decimal>>'
Two questions:两个问题:
decimal
version of Sum<>
?Sum<>
的decimal
版本却失败了?decimal?
decimal?
version of that function in System.Linq.Queryable
? System.Linq.Queryable
中该函数的版本? public static decimal? Sum<TSource>(this IQueryable<TSource> source, Expression<Func<TSource, decimal?>> selector);
If that worked, technically, you could call that SumOrDefault
function with something that decimal cannot convert yet still respect your where
(
a custom "unsummable" class would, for example).string
如果这有效,从技术上讲,您可以使用小数无法转换但仍然尊重您的
where
东西调用SumOrDefault
函数(例如,自定义“unsummable”类的
)。string
And it can't find the decimal?
它找不到
decimal?
version of the function because it doesn't know which type to convert to safely.函数的版本,因为它不知道要安全地转换为哪种类型。
C# doesn't have a way to filter a type to just numerics, AFAIK, so you will have to overload them manually like it's 2001: 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.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.