Getting sub property names strongly typed

前端 未结 2 1221
自闭症患者
自闭症患者 2021-01-16 06:40

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 st         


        
2条回答
  •  无人共我
    2021-01-16 06:51

    This is a modified version of something I might have found here on StackOVerflow:

    public static class GetPropertyNameExtension
    {
        public static string GetPropertyName(this Expression> propertyExpression)
        {
            return propertyExpression.Body.GetMemberExpression().GetPropertyName();
        }
    
        public static string GetPropertyName(this Expression> propertyExpression)
        {
            return propertyExpression.Body.GetMemberExpression().GetPropertyName();
        }
    
        public static string GetPropertyName(this MemberExpression memberExpression)
        {
            if (memberExpression == null)
            {
                return null;
            }
    
            if (memberExpression.Member.MemberType != MemberTypes.Property)
            {
                return null;
            }
    
            var child = memberExpression.Member.Name;
            var parent = GetPropertyName(memberExpression.Expression.GetMemberExpression());
    
            return parent == null ?
                child
                : parent + "." + child;
        }
    
        public static MemberExpression GetMemberExpression(this Expression expression)
        {
            if (expression is MemberExpression)
                return (MemberExpression)expression;
    
            if (expression is UnaryExpression)
                return (MemberExpression)((UnaryExpression)expression).Operand;
    
            return null;
        }
    }
    

提交回复
热议问题