C#表达式-获取默认值还是转换int?到int

本文关键字:int 转换 表达式 获取 默认值 | 更新日期: 2023-09-27 18:26:14

我有一个类似的类

public class GrouppedStockGift
{
    public DateTime? TimeCreated { get; set; }
    public int? StoreID { get; set; }
    public int? UserCreated { get; set; }
    public int? WorksID { get; set; }
    public int? WorkOrderCode { get; set; }
    public decimal? GiftPrice { get; set; }
    public decimal? GiftMoney { get; set; }
    public int SaleCount { get; set; }
}

我创建了一个动态表达式生成器,在某些情况下,我需要int的convert int? to intgetdefaultvalue,例如

var sumMethodint = typeof(Enumerable).GetMethods()
                       .Single(x => x.Name == "Sum"
                                 && x.GetParameters().Count() == 2
                                 && x.GetParameters()[1]
                                     .ParameterType
                                     .GetGenericArguments()[1] == typeof(int?));
sumMethodint = sumMethodint.MakeGenericMethod(typeof(GrouppedStockGift));
Expression<Func<GrouppedStockGift, int?>> SaleCount = y => y.SaleCount;
var SaleCountExtractor = Expression.Call(sumMethodint, parameter, SaleCount);
bindings.Add(
              Expression.Bind(
                           typeof(GrouppedStockGift).GetProperty("SaleCount"),
                           SaleCountExtractor));

但当执行最后一行时,返回了类型错误的异常
因为SaleCount是int,但sum方法返回int
有人能帮我吗?

C#表达式-获取默认值还是转换int?到int

您必须将Expression.Call行更改为

var SaleCountExtractor = Expression.Call(Expression.Call(sumMethodint, parameter, SaleCount), "GetValueOrDefault", Type.EmptyTypes);

在上述代码中

Expression.Call(exp, "GetValueOrDefault", Type.EmptyTypes);

获取int 的默认值

我认为问题在于您决定使用返回int?Sum重载。您应该使用另一个重载,它获取类型为Func<T, int>的selecotr并返回int

var parameter = Expression.Parameter(typeof (IEnumerable<GrouppedStockGift>));
var sumMethodint = typeof(Enumerable).GetMethods()
            .Single(x => x.Name == "Sum"
                        && x.GetParameters().Count() == 2
                        && x.GetParameters()[1]
                            .ParameterType
                            .GetGenericArguments()[1] == typeof(int));
sumMethodint = sumMethodint.MakeGenericMethod(typeof(GrouppedStockGift));
Expression<Func<GrouppedStockGift, int>> saleCount = y => y.SaleCount;
var saleCountExtractor = Expression.Call(sumMethodint, parameter, saleCount);
bindings.Add(Expression.Bind(typeof(GrouppedStockGift).GetProperty("SaleCount"),
                             saleCountExtractor));