C# 如何从linq表达式中获取嵌套属性名(作为展平值)?
我得出了以下结论。但代码看起来并不漂亮:C# 如何从linq表达式中获取嵌套属性名(作为展平值)?,c#,linq-expressions,C#,Linq Expressions,我得出了以下结论。但代码看起来并不漂亮: public static class GenericHelper<TEntity> { //This method uses my extension method, but it returns plain property name public static string GetPropertyName<TProperty>(Expression<Func<TEntity, TProperty
public static class GenericHelper<TEntity> {
//This method uses my extension method, but it returns plain property name
public static string GetPropertyName<TProperty>(Expression<Func<TEntity, TProperty>> propertyExpression) {
return propertyExpression.GetPropertyName();
}
//This method is used to return nested property name as dot-separated value
public static string GetPropertyFlattenName<TProperty>(Expression<Func<TEntity, TProperty>> propertyExpression) {
//TODO: check TEntity, if needed. Now it's ignored
var member = propertyExpression.Body as MemberExpression;
if (member == null) {
throw new ArgumentException(String.Format(
"Expression '{0}' refers to a method, not a property.", propertyExpression));
}
var propertyInfo = member.Member as PropertyInfo;
if (propertyInfo == null) {
throw new ArgumentException(string.Format(
"Expression '{0}' refers to a field, not a property.", propertyExpression));
}
//Suppposing it's the only one for this method
var parameter = propertyExpression.Parameters[0].Name;
return propertyExpression.Body.ToString().Replace(string.Format("{0}.", parameter), "");
}
}
公共静态类GenericHelper{
//此方法使用我的扩展方法,但它返回纯属性名
公共静态字符串GetPropertyName(表达式propertyExpression){
返回propertyExpression.GetPropertyName();
}
//此方法用于将嵌套属性名称作为点分隔值返回
公共静态字符串GetPropertyFlatName(表达式propertyExpression){
//TODO:如果需要,检查tenty。现在它被忽略了
var member=propertyExpression.Body作为MemberExpression;
if(成员==null){
抛出新ArgumentException(String.Format(
表达式“{0}”引用的是方法,而不是属性。“,propertyExpression”);
}
var propertyInfo=member.member作为propertyInfo;
如果(propertyInfo==null){
抛出新ArgumentException(string.Format(
表达式“{0}”引用的是字段,而不是属性。“,propertyExpression”);
}
//假设这是唯一一种这种方法
var参数=propertyExpression.Parameters[0]。名称;
返回propertyExpression.Body.ToString().Replace(string.Format(“{0}.”,参数),”);
}
}
我发现没有办法以更智能和优雅的方式提取扁平属性名称
只需指定:第一种方法的用法如下:
GenericHelper<MyEntity>.GetPropertyName(entity => entity.Property)
GenericHelper.GetPropertyName(实体=>entity.Property)
但是如果我有一个嵌套属性,比如entity.property.NestedProperty,我需要使用第二个方法:
GenericHelper<MyEntity>.GetPropertyFlattenName(entity => entity.Property.NestedProperty)
GenericHelper.GetPropertyFlatName(实体=>entity.Property.NestedProperty)
要返回“Property.NestedProperty”而不是“NestedProperty”。您可以返回
propertyInfo.Name
。也许您不应该使用泛型类类型参数,而应该向方法添加泛型参数,以便将其用作扩展方法。很抱歉,不清楚,我编辑了我的问题,以解释为什么propertyInfo.Name不适合我(我需要点分隔格式)。