我有这样的代码:
string PropertyName<T>(Expression<Func<T>> expression)
{
var body = expression.Body as MemberExpression;
if (body == null)
{
body = ((UnaryExpression)expression.Body).Operand as MemberExpression;
}
return body.Member.Name;
}
我以这种方式使用它:
Console.WriteLine(PropertyName(() => this.Property));
在屏幕上打印Property
现在我想改变它:
Console.WriteLine(PropertyName(() => this.OtherObject.Property));
会给我OtherObject.Property
而不只是Property
。这甚至可能吗?
目的是从代码创建对依赖项属性的绑定,而无需对属性名称进行硬编码。
我还有一个问题body
在5
行等于null
的时间是什么时候?我无意识地复制了这段代码并将其留在原处,但这种情况似乎永远不会成真。
答案 0 :(得分:1)
string PropertyName<T>(Expression<Func<T>> expression)
{
var body = expression.Body as MemberExpression;
if (body == null)
{
body = ((UnaryExpression)expression.Body).Operand as MemberExpression;
}
return string.Join(".", GetPropertyNames(body).Reverse());
}
private IEnumerable<string> GetPropertyNames(MemberExpression body)
{
while (body != null)
{
yield return body.Member.Name;
var inner = body.Expression;
switch (inner.NodeType)
{
case ExpressionType.MemberAccess:
body = inner as MemberExpression;
break;
default:
body = null;
break;
}
}
}