本文介绍了给定一个成员访问拉姆达EX pression,将其转换为特定的字符串重新presentation具有完全的访问路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
给定一个
防爆pression< Func键< T,对象>>
(例如:X => x.Prop1.SubProp),我想创建一个字符串Prop1.SubProp深所必需的。
在一个单一的接入(例如:X => x.Prop1)的情况下,我可以很容易地做到这一点有:
MemberEx pression体=(EX pression.Body.NodeType ==前pressionType.Convert)? (MemberEx pression)((UnaryEx pression)EX pression.Body).Operand:(MemberEx pression)EX pression.Body;
返回body.Member.Name;
然而,如果有更深入的排料,例如X => x.Prop1.SubProp1,这只能得到最深层的名称,例如: SubProp1,而不是Prop1.SubProp1
反正是有访问一个lambda EX pression全属性路径?
解决方案
公共字符串GetPath< T>(出pression< Func键< T,对象>>表达式)
{
VAR堆栈=新的堆栈<字符串>();
MemberEx pression我。
开关(expr.Body.NodeType)
{
案前pressionType.Convert:
案前pressionType.ConvertChecked:
VAR UE = expr.Body为UnaryEx pression;
我=((UE = NULL)ue.Operand:!?NULL)作为MemberEx pression;
打破;
默认:
我= expr.Body为MemberEx pression;
打破;
}
而(我!= NULL)
{
stack.Push(me.Member.Name);
我= me.Ex pression为MemberEx pression;
}
返回的string.join(,stack.ToArray()。);
}
Given an
Expression<Func<T, object>>
(e.g. x => x.Prop1.SubProp), I want to create a string "Prop1.SubProp" for as deep as necessary.
In the case of a single access (e.g. x => x.Prop1), I can easily do this with:
MemberExpression body = (expression.Body.NodeType == ExpressionType.Convert) ? (MemberExpression)((UnaryExpression)expression.Body).Operand : (MemberExpression)expression.Body;
return body.Member.Name;
However, if there is deeper nesting, e.g. x => x.Prop1.SubProp1, this only gets the most deeply nested name, e.g. "SubProp1" instead of "Prop1.SubProp1"
Is there anyway to access the full property path of a lambda expression?
解决方案
public string GetPath<T>(Expression<Func<T, object>> expr)
{
var stack = new Stack<string>();
MemberExpression me;
switch (expr.Body.NodeType)
{
case ExpressionType.Convert:
case ExpressionType.ConvertChecked:
var ue = expr.Body as UnaryExpression;
me = ((ue != null) ? ue.Operand : null) as MemberExpression;
break;
default:
me = expr.Body as MemberExpression;
break;
}
while (me != null)
{
stack.Push(me.Member.Name);
me = me.Expression as MemberExpression;
}
return string.Join(".", stack.ToArray());
}
这篇关于给定一个成员访问拉姆达EX pression,将其转换为特定的字符串重新presentation具有完全的访问路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!