4

可以用 代替Expression<Func<Nullable<TValue>>>Expression<Func<TValue>>

价值在哪里Nullable<TValue>.GetValueOrDefault()

4

1 回答 1

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);
}
于 2012-11-09T08:32:37.960 回答