表達式:使用API建立表達式樹(3)

1、DebugInfoExpression:發出或清除調試信息的序列點。 這容許調試器在調試時突出顯示正確的源代碼。ide

        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用的機會也很少,就沒深究了ui

2、DefaultExpression :表示類型或空表達式的默認值。有點相似泛型的默認值操做,沒什麼難度:
下面摘自MSDN

spa

Expression defaultExpr = Expression.Default(
                            typeof(byte)
                        );

// 顯示錶達式
Console.WriteLine(defaultExpr.ToString());

// 建立表達式樹,並執行
Console.WriteLine(
    Expression.Lambda<Func<byte>>(defaultExpr).Compile()());

// 顯示結果:
//
// default(Byte)
// 0
相關文章
相關標籤/搜索