用value替换lambda表达式中的nullable参数

时间:2012-11-09 08:26:03

标签: c# lambda

是否可以将Expression<Func<Nullable<TValue>>>替换为Expression<Func<TValue>>

值为Nullable<TValue>.GetValueOrDefault()

1 个答案:

答案 0 :(得分:3)

  

是否可以将Expression<Func<Nullable<TValue>>>替换为Expression<Func<TValue>>

当然 - 这只是包装lambda的最外层结果:

static void Main() {

    Expression<Func<int?>> x = () => 1, y = () => null;
    Expression<Func<int>> a = DeNullify(x), b = DeNullify(y);

    Console.WriteLine(x.Compile()()); // 1
    Console.WriteLine(y.Compile()()); // {blank; null}

    Console.WriteLine(a.Compile()()); // 1
    Console.WriteLine(b.Compile()()); // 0 
}
public static Expression<Func<TValue>> DeNullify<TValue>(
    Expression<Func<TValue?>> expression) where TValue : struct
{
    return Expression.Lambda<Func<TValue>>(
        Expression.Call(expression.Body, "GetValueOrDefault", null),
        expression.Parameters);
}