一、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, , , , );
var gen = DebugInfoGenerator.CreatePdbGenerator(); var exp = Expression.Divide(Expression.Constant(), Expression.Subtract(Expression.Constant(), Expression.Constant()));
var block = Expression.Block(di, exp); Expression.Lambda(block, new ParameterExpression[]).CompileToMethod(meth, gen); var newtype = type.CreateType();
asm.Save("tmp.dll");
newtype.GetMethod("go").Invoke(null, new object[]);
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)
//