gpt4 book ai didi

c# - 无法从 'System.Linq.Expressions.Expression>' 转换为 'System.Linq.Expressions.Expression>'

转载 作者:行者123 更新时间:2023-12-04 10:52:53 30 4
gpt4 key购买 nike

为什么以下不编译?

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<> 的版本?
  • 为什么找不到decimal? System.Linq.Queryable 中该函数的版本?
  •         public static decimal? Sum<TSource>(this IQueryable<TSource> source, Expression<Func<TSource, decimal?>> selector);

    最佳答案

    如果这行得通,从技术上讲,你可以称之为 SumOrDefault具有十进制无法转换但仍尊重您的where的功能(例如,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.

    关于c# - 无法从 'System.Linq.Expressions.Expression<System.Func<T, V?>>' 转换为 'System.Linq.Expressions.Expression<System.Func<T, decimal>>',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59380420/

    30 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com