获取子属性名称强类型 [英] Getting sub property names strongly typed
问题描述
使用数据绑定对象控件和网格我讨厌怎样的属性名称将是神奇的字符串,所以我创建了一个非常简单的方法如下:
With databinding objects to controls and grids I hated how the property names would be magic strings, so I created a very simple method as follows:
public static string GetPropertyName<PropertyType>(Expression<Func<T, PropertyType>> expressionForProperty)
{
MemberExpression expression = expressionForProperty.Body as MemberExpression;
return expression.Member.Name;
}
这让我用code,如:
This lets me use code such as:
Product.GetPropertyName(m => m.Name)
要返回名。
这完全适用于基本对象。但是,如果我改变了方法调用是:
This works perfectly for basic objects. However if I change the method call to be:
Product.GetPropertyName(m => m.ProductCategory.Name)
这也返回名。但是,为了使数据绑定工作,我需要它返回ProductCategory.Name。有没有一种方法,我可以通过改变方法得到这个getPropertyName方法?
This also returns "Name". But in order for the databinding to work, I would need it to return "ProductCategory.Name". Is there a way I can get to this by changing the method "GetPropertyName"?
一个可能的解决方法是做到这一点:
A possible workaround would be to do this:
string test = Product.GetPropertyName(p => p.ProductCategory) + "." + ProductCategory.GetPropertyName(pc => pc.Name)
但是,这不是一种纯溶液
However, this isn't a neat solution.
推荐答案
我想出了这似乎工作如下:
I came up with the following which seems to work:
public static string GetComplexPropertyName<PropertyType>(Expression<Func<T, PropertyType>> expressionForProperty)
{
// get the expression body
Expression expressionBody = expressionForProperty.Body as MemberExpression;
string expressionAsString = null;
// all properties bar the root property will be "convert"
switch (expressionBody.NodeType)
{
case ExpressionType.Convert:
case ExpressionType.ConvertChecked:
UnaryExpression unaryExpression = expressionBody as UnaryExpression;
if (unaryExpression != null)
{
expressionAsString = unaryExpression.Operand.ToString();
}
break;
default:
expressionAsString = expressionBody.ToString();
break;
}
// makes ure we have got an expression
if (!String.IsNullOrWhiteSpace(expressionAsString))
{
// we want to get rid of the first operand as it will be the root type, so get the first occurence of "."
int positionOfFirstDot = expressionAsString.IndexOf('.');
if (positionOfFirstDot != -1)
{
return expressionAsString.Substring(positionOfFirstDot + 1, expressionAsString.Length - 1 - positionOfFirstDot);
}
}
return string.Empty;
}
这篇关于获取子属性名称强类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!