![](/img/trans.png)
[英]Cannot convert expression type 'lambda expression' to return type 'System.Linq.Expressions.Expression<System.Func<IProduct,string,bool>>'
[英]cannot convert from 'System.Linq.Expressions.Expression<System.Func<T, V?>>' to 'System.Linq.Expressions.Expression<System.Func<T, decimal>>'
为什么以下不编译?
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
版本却失败了?decimal?
System.Linq.Queryable
中该函数的版本? public static decimal? Sum<TSource>(this IQueryable<TSource> source, Expression<Func<TSource, decimal?>> selector);
如果这有效,从技术上讲,您可以使用小数无法转换但仍然尊重您的where
东西调用SumOrDefault
函数(例如,自定义“unsummable”类的
)。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.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.