C# 将lambda表达式中的可空参数替换为值

C# 将lambda表达式中的可空参数替换为值,c#,lambda,C#,Lambda,是否可以将表达式替换为表达式 其中值可为null。GetValuerDefault() 是否可以将表达式替换为表达式 当然-这只是包装lambda的最外层结果: static void Main() { Expression<Func<int?>> x = () => 1, y = () => null; Expression<Func<int>> a = DeNullify(x), b = DeNullify(y);

是否可以将
表达式
替换为
表达式

其中值可为null。GetValuerDefault()

是否可以将
表达式
替换为
表达式

当然-这只是包装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);
}
static void Main(){
表达式x=()=>1,y=()=>null;
表达式a=去核化(x),b=去核化(y);
Console.WriteLine(x.Compile()());//1
Console.WriteLine(y.Compile()());//{blank;null}
Console.WriteLine(a.Compile()());//1
Console.WriteLine(b.Compile()());//0
}
公共静态表达式去噪(
表达式),其中TValue:struct
{
返回表达式.Lambda(
Expression.Call(Expression.Body,“GetValueOrDefault”,null),
表达式(参数);
}

顺便说一句,
表达式
没有任何参数我的意思是:问题标题不符合示例;除非你指的是泛型类型参数?