0

我有下面的函数,当我调用它时返回“Test” GetPropertyName<Model>(x => x.Test)
如何返回深度调用,例如:User.UserName。
我想看看User.UserName我什么时候打电话GetPropertyName<Model>(x => x.User.FullName)

谢谢

public static string GetPropertyName<T>(Expression<Func<T, object>> expression)
{
    var body = expression.Body as MemberExpression;
    if (body == null)
    {
        body = ((UnaryExpression)expression.Body).Operand as MemberExpression;
    }
    if (body != null)
    {
        return body.Member.Name;
    }
    return null;
}

编辑 1

这是我的课:

public class Place : BaseEntity
{
     public virtual User UserManager { get; set; }
}

public class User : BaseEntity
{
     public virtual string FullName { get; set; }
}
4

1 回答 1

2

此方法遍历表达式中的节点,将节点转换为属性并将其添加到列表中。

private IList<PropertyInfo> GetProperties<T>(Expression<Func<T, object>> fullExpression)
{
    Expression expression;
    switch (fullExpression.Body.NodeType)
    {
        case ExpressionType.Convert:
        case ExpressionType.ConvertChecked:
            var ue = fullExpression.Body as UnaryExpression;
            expression = ((ue != null) ? ue.Operand : null) as MemberExpression;
            break;
        default:
            expression = fullExpression.Body as MemberExpression;
            break;
    }

    var props = new List<PropertyInfo>();

    while(expression != null && expression.NodeType == ExpressionType.MemberAccess)
    {
        var memberExp = expression as MemberExpression;

        if(memberExp.Member is FieldInfo)
            throw InvalidExpressionException.FieldFound;

        var prop = memberExp.Member as PropertyInfo;
        props.Insert(0, prop);

        expression = memberExp.Expression;
    }
    return props;
}

如果你想得到这样的字符串:User.UserName,你可以这样做:

var props = GetProperties<Model>(m => m.User.Username);
var propNames = props.Select(p => p.Name);
string names = string.Join(".", propNames);
于 2013-09-07T16:32:44.757 回答