带有 Convert 和 TryCatch 的 C# 表达式

我需要将两个输入双数相除,并使用 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。


蛊毒传说
浏览 180回答 2
2回答

慕尼黑5688855

我需要将两个输入双数相除,并使用 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。

慕森卡

这有什么问题?try{&nbsp; var e_DBZ = dInput1 / dInput2;}catch (Exception e){&nbsp; // Handle Divide by Zero error&nbsp; Console.WriteLine(e.Message);}
打开App,查看更多内容
随时随地看视频慕课网APP