【问题标题】:cannot convert from 'System.Linq.Expressions.Expression<System.Func<T, V?>>' to 'System.Linq.Expressions.Expression<System.Func<T, decimal>>'无法从 'System.Linq.Expressions.Expression<System.Func<T, V?>>' 转换为 'System.Linq.Expressions.Expression<System.Func<T, decimal>>'
【发布时间】:2020-04-10 07:42:30
【问题描述】:

为什么下面的不能编译?

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>>'

两个问题:

  • 为什么尝试调用decimal 版本的Sum&lt;&gt; 却失败了?
  • 为什么在System.Linq.Queryable中找不到该函数的decimal?版本?
        public static decimal? Sum<TSource>(this IQueryable<TSource> source, Expression<Func<TSource, decimal?>> selector);

【问题讨论】:

    标签: c# generics roslyn iqueryable


    【解决方案1】:

    如果这行得通,从技术上讲,您可以使用十进制无法转换但仍尊重您的 where 的东西调用 SumOrDefault 函数(string 自定义“unsummable”类将示例)。

    而且它找不到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.
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多