所以,假设我在C#中有以下表达式:
Expression<Func<string>> expr = () => foo.Bar;
如何提取对foo的引用?
答案 0 :(得分:47)
我有同样的问题,但有点复杂,Darin Dimitrov的回答给了我一个良好的开端。我会在这里发布我的结果,尽管事实上这是一个“旧”问题。
this.textBox.Text // where 'this' has type 'Form'
...等同于以下表达式树:
. +====================+
. | MemberExpression |
. +====================+
# | |
# .Expression | | .Member
# v v
. +------------------+ +------------+
. | MemberExpression | | MemberInfo |
. +------------------+ +------------+
# | | .Name = "Text"
# .Expression | | .Member .MemberType = Property
# v v
. +--------------------+ +------------+
. | ConstantExpression | | MemberInfo |
. +--------------------+ +------------+
# .Value = this .Name = "textBox"
# .Type = typeof(Form) .MemberType = Field
此表达式树中您实际获得对象引用的唯一位置来自ConstantExpression
:它允许您获取对this
的引用。因此,在此树中获取任何对象引用的基本思想如下:
沿着.Expression
轴下降到表达式树,直到到达ConstantExpression
节点。
抓住该节点的.Value
属性。这是根对象引用(即上例中的this
)。
使用表达式树中的反射和MemberInfo
节点,获取对象引用,然后以“向上”的方式返回表达式树。
这里有一些代码可以证明这一点:
Expression expr = ...; // <-- initially set to the expression tree's root
var memberInfos = new Stack<MemberInfo>();
// "descend" toward's the root object reference:
while (expr is MemberExpression)
{
var memberExpr = expr as MemberExpression;
memberInfos.Push(memberExpr.Member);
expr = memberExpr.Expression
}
// fetch the root object reference:
var constExpr = expr as ConstantExpression;
var objReference = constExpr.Value;
// "ascend" back whence we came from and resolve object references along the way:
while (memberInfos.Count > 0) // or some other break condition
{
var mi = memberInfos.Pop();
if (mi.MemberType == MemberTypes.Property)
{
objReference = objReference.GetType()
.GetProperty(mi.Name)
.GetValue(objReference, null);
}
else if (mi.MemberType == MemberTypes.Field)
{
objReference = objReference.GetType()
.GetField(mi.Name)
.GetValue(objReference);
}
}
Form.textBox.Text // where 'textBox' is a static member of type 'Form'
...导致不同的表达式树。请注意左下角的空引用:
. +====================+
. | MemberExpression |
. +====================+
# | |
# .Expression | | .Member
# v v
. +------------------+ +------------+
. | MemberExpression | | MemberInfo |
. +------------------+ +------------+
# | | .Name = "Text"
# .Expression | | .Member .MemberType = Property
# v v
. null +------------+
. | MemberInfo |
. +------------+
# .Name = "textBox"
# .MemberType = Field
# .DeclaringType = typeof(Form)
在这里,您无法通过等待ConstantExpression
来停止“下降”阶段。而是在到达空引用时停止降序。接下来,检索根对象引用,如下所示:
var mi = memberInfos.Pop();
objReference = mi.DeclaringType
.GetField(member.Name, BindingFlags.Static) // or .GetProperty!
.GetValue(null);
从此开始的“提升”阶段与以前相同。
肯定有更多的情况(例如命名参数作为根对象),但我希望到现在为止,我已经有了基本的想法,所以我会在这里切断。
答案 1 :(得分:38)
Expression<Func<string>> expr = () => foo.Bar;
var me = (MemberExpression)((MemberExpression)expr.Body).Expression;
var ce = (ConstantExpression)me.Expression;
var fieldInfo = ce.Value.GetType().GetField(me.Member.Name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
var value = (Foo)fieldInfo.GetValue(ce.Value);
答案 2 :(得分:2)
有一个更简单的解决方案:
var pExpression = ((MemberExpression)expr.Body);
var bindingObject = Expression.Lambda(((MemberExpression)pExpression.Expression)).Compile().DynamicInvoke();
答案 3 :(得分:0)
谢谢,staks - 你的榜样给了我很多帮助!所以我想为第一个案例做一些补充:
要从方法中提取值,应该替换代码:
// fetch the root object reference:
var constExpr = expr as ConstantExpression;
var objReference = constExpr.Value;
代码:
var newExpression = expr as NewExpression;
if (newExpression != null)
{
return newExpression.Constructor.Invoke(newExpression.Arguments.Select(GetObjectValue).ToArray());
}
var methodCallExpr = expr as MethodCallExpression;
if (methodCallExpr != null)
{
var value = methodCallExpr.Method.Invoke(methodCallExpr.Object == null
? null
: GetObjectValue(methodCallExpr.Object),
methodCallExpr.Arguments.Select(GetObjectValue).ToArray());
return value;
}
// fetch the root object reference:
var constExpr = expr as ConstantExpression;
if (constExpr == null)
{
return null;
}
var objReference = constExpr.Value;
// ... the rest remains unchanged
这样可以从以下表达式中提取值:
aInstane.MethodCall(anArgument1, anArgument2) or
AType.MethodCall(anArgument1, anArgument2) or
new AType().MethodCall(anArgument1, aInstane.MethodCall(anArgument2, anArgument3))
答案 4 :(得分:0)
这是我在单元测试中使用的:
internal static INotifyPropertyChanged SubModel < T, TProperty > (T model, Expression < Func < T, TProperty >> pickProperty) where T: INotifyPropertyChanged {
MemberExpression memberExpression = (MemberExpression) pickProperty.Body;
ParameterExpression parameterExpression = pickProperty.Parameters[0];
Expression mem = memberExpression.Expression;
var delegateType = typeof(Func < , > ).MakeGenericType(typeof(T), mem.Type);
LambdaExpression lambdaExpression = Expression.Lambda(delegateType, mem, parameterExpression);
object subModel = lambdaExpression.Compile().DynamicInvoke(model);
return subModel as INotifyPropertyChanged ? ? model;
}