C#表达式 - Getdefault值还是转换为int?到int

时间:2014-10-12 09:39:03

标签: c# linq expression nhlambdaextensions

我有一个类如下

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; }
}

我有创建动态表达式构建器,在某些情况下我需要convert int? to intgetdefaultvalue的int例如

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?
任何人都可以帮助我吗?

2 个答案:

答案 0 :(得分:0)

您必须将Expression.Call行更改为

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

在上面的代码中

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

获取int的默认值

答案 1 :(得分:0)

我认为您决定使用返回Sum的{​​{1}}重载。你应该使用另一个重载来获得int?类型的selecotr并返回Func<T, int>

int