首页 > 学院 > 开发设计 > 正文

表达式:使用API创建表达式树(3)

2019-11-17 03:18:18
字体:
来源:转载
供稿:网友

表达式:使用API创建表达式树(3)

一、DebugInfoExPRession:发出或清除调试信息的序列点。 这允许调试器在调试时突出显示正确的源代码。

        static void Main(string[] args)        {            var asm = AppDomain.CurrentDomain.DefineDynamicAssembly(new AssemblyName("foo"), System.Reflection.Emit.AssemblyBuilderaccess.RunAndSave);            var mod = asm.DefineDynamicModule("mymod", true);            var type = mod.DefineType("baz", TypeAttributes.Public);            var meth = type.DefineMethod("go", MethodAttributes.Public | MethodAttributes.Static);            var sdi = Expression.SymbolDocument("TestDebug.cs");            var di = Expression.DebugInfo(sdi, 2, 2, 2, 12);            var gen = DebugInfoGenerator.CreatePdbGenerator();            var exp = Expression.Divide(Expression.Constant(2), Expression.Subtract(Expression.Constant(4), Expression.Constant(4)));            var block = Expression.Block(di, exp);            Expression.Lambda(block, new ParameterExpression[0]).CompileToMethod(meth, gen);            var newtype = type.CreateType();            asm.Save("tmp.dll");            newtype.GetMethod("go").Invoke(null, new object[0]);            Console.WriteLine(" ");        }

运行了下: 未经处理的异常: System.Reflection.TargetInvocationException: 调用的目标发生了异 常。 ---> System.DivideByZeroException: 尝试除以零。 在 baz.go() 位置 TestDebug.cs:行号 2 --- 内部异常堆栈跟踪的结尾 --- 在 System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor) 在 System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Objec t[] parameters, Object[] arguments) 在 System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invoke Attr, Binder binder, Object[] parameters, CultureInfo culture) 在 System.Reflection.MethodBase.Invoke(Object obj, Object[] parameters) 在 Consoleapplication2.Program.Main(String[] args) 位置 d:/平台/演示程序/Debu gInfoExpressionApplication2/ConsoleApplication2/Program.cs:行号 72那个 “在 baz.go() 位置 TestDebug.cs:行号 2”就是DebugInfoExpression产生的效果,试了几种其他的方法,不能出现类似的效果,说Debug info 只会出现在编译过的方法。DebugInfoExpression用的机会也不多,就没深究了

二、DefaultExpression :表示类型或空表达式的默认值。有点类似泛型的默认值操作,没什么难度:下面摘自MSDN

Expression defaultExpr = Expression.Default(                            typeof(byte)                        );// 显示表达式Console.WriteLine(defaultExpr.ToString());// 创建表达式树,并执行Console.WriteLine(    Expression.Lambda<Func<byte>>(defaultExpr).Compile()());// 显示结果://// default(Byte)// 0


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表