2 回答
TA贡献1848条经验 获得超2个赞
我需要将两个输入双数相除,并使用 try catch 来处理 DivideByZeroException 等。
ParameterExpression dInput1 = Expression.Parameter(typeof(double), "input1");
ParameterExpression dInput2 = Expression.Parameter(typeof(double), "input2");
ParameterExpression e_DBZ = Expression.Parameter(typeof(DivideByZeroException));
ParameterExpression e_ = Expression.Parameter(typeof(Exception));
var _calc = Expression.Divide(dInput1, dInput2);
MethodInfo _consolewrite = typeof(Console).GetMethod("WriteLine",new Type[] { typeof(string) });
MethodCallExpression _output = Expression.Call(null, _consolewrite, Expression.Convert(Expression.Constant(_calc,typeof(double)), typeof(string)));
var _catch_DivideByZeroException = Expression.Catch(e_DBZ, Expression.Call(null, _consolewrite, Expression.Property(e_DBZ, "Message")));
var _catch_Exception = Expression.Catch(e_, Expression.Call(null, _consolewrite, Expression.Property(e_DBZ, "Message")));
var _calc_Block = Expression.Block(_calc, Expression.Constant(0));
var _try = Expression.TryCatch(_calc_Block, _catch_DivideByZeroException, _catch_Exception);
var _lambda = Expression.Lambda<Func<double,double, double>>(_try, dInput1,dInput2);
Console.WriteLine(_lambda.Body);
Console.WriteLine(_lambda.Compile().Invoke(1,0));
但是 Expression.Convert 会抛出 System.ArgumentException。
TA贡献1806条经验 获得超8个赞
这有什么问题?
try
{
var e_DBZ = dInput1 / dInput2;
}
catch (Exception e)
{
// Handle Divide by Zero error
Console.WriteLine(e.Message);
}
- 2 回答
- 0 关注
- 178 浏览
添加回答
举报