繁体   English   中英

无法从“System.Linq.Expressions.Expression”转换<System.Func<T, V?> &gt;&#39; 到 &#39;System.Linq.Expressions.Expression <System.Func<T, decimal> &gt;&#39;

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM