![](/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.