使用 .NET Reflector 掌握表达式树






4.60/5 (4投票s)
在我的上一篇博文中,我收到了很多关于如何掌握表达式树创建的询问。
在我的上一篇 文章 之后,我收到了很多关于如何掌握 表达式树 创建的询问。
答案是 .NET Reflector。
在那篇文章中,我需要为这个表达式生成一个表达式树
Expression<Func<object, object>> expression = o => ((object)((SomeType)o).Property1);
我只是在 Visual Studio 2010 中编译了这段代码,在 .NET Reflector 中加载了程序集,并将其反编译为 C#,且不进行优化(视图 –> 选项 –> 反编译器 –> 优化:无)。
反编译后的代码如下所示
Expression<Func<object, object>> expression;
ParameterExpression CS$0$0000;
ParameterExpression[] CS$0$0001;
expression = Expression.Lambda<Func<object, object>>
(Expression.Convert(Expression.Property(Expression.Convert
(CS$0$0000 = Expression.Parameter(typeof(object), "o"),
typeof(SomeType)), (MethodInfo) methodof(SomeType.get_Property1)),
typeof(object)), new ParameterExpression[] { CS$0$0000 });
在为变量赋予有效的 C# 名称并对代码进行整理后,我得到了这个
ParameterExpression parameter = Expression.Parameter(typeof(object), "o");
Expression<Func<object, object>> expression =
Expression.Lambda<Func<object, object>>(
Expression.Convert(
Expression.Property(
Expression.Convert(
parameter,
typeof(SomeType)
),
"Property1"
),
typeof(object)
),
parameter
);
很简单,不是吗?