簡體   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