如何创建,要么抛出一个异常或返回基于条件值的表达式? [英] How can I create an expression that either throws an exception or returns a value based on a condition?
问题描述
我挣扎建立,如果条件为真抛出异常表达,如果它是假的,它应该返回一个值,但我总是得到的ArgumentException
:
I'm struggling to build an expression that if the condition is true throws an exception and if it's false that it should return a value but I'm always getting the ArgumentException
:
var expr =
Expression.Condition(
Expression.Equal(Expression.Constant(0), Expression.Constant(0)),
Expression.Throw(Expression.Constant(new DivideByZeroException())),
Expression.Constant(1));
var lambda = Expression.Lambda<Func<int>>(expr);
var result = lambda.Compile()();
如果我把 Expression.Empty()
作为条件
的第三个参数它然后运行,但如果条件是假的我没有得到期望的结果。
If I put Expression.Empty()
as the third argument of the Condition
it then runs but I don't get the desired result if the condition is false.
推荐答案
该做的。
var expr =
Expression.Block(
Expression.IfThen(
Expression.Equal(Expression.Constant(1), Expression.Constant(1)),
Expression.Throw(
Expression.New(typeof(DivideByZeroException))
)
),
Expression.Constant(1)
);
var lambda = Expression.Lambda<Func<int>>(expr);
var result = lambda.Compile()();
条件
更类似于三元运算符。所以,你在写什么在C#更加等价于:
Conditional
is more similar to the ternary operator. So what you were writing was more equivalent to in C#:
return (0 == 0) ? throw new DivideByZeroException() : 1;
我改变了你的不变异常动态创建的,我假设是首选。
I changed your constant exception to a dynamically created one, I'm assuming that is preferred.
这篇关于如何创建,要么抛出一个异常或返回基于条件值的表达式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!