Retrieving Property name from lambda expression

前端 未结 21 1701
迷失自我
迷失自我 2020-11-21 11:12

Is there a better way to get the Property name when passed in via a lambda expression? Here is what i currently have.

eg.

GetSortingInfo         


        
21条回答
  •  被撕碎了的回忆
    2020-11-21 12:03

    Starting with .NET 4.0 you can use ExpressionVisitor to find properties:

    class ExprVisitor : ExpressionVisitor {
        public bool IsFound { get; private set; }
        public string MemberName { get; private set; }
        public Type MemberType { get; private set; }
        protected override Expression VisitMember(MemberExpression node) {
            if (!IsFound && node.Member.MemberType == MemberTypes.Property) {
                IsFound = true;
                MemberName = node.Member.Name;
                MemberType = node.Type;
            }
            return base.VisitMember(node);
        }
    }
    

    Here is how you use this visitor:

    var visitor = new ExprVisitor();
    visitor.Visit(expr);
    if (visitor.IsFound) {
        Console.WriteLine("First property in the expression tree: Name={0}, Type={1}", visitor.MemberName, visitor.MemberType.FullName);
    } else {
        Console.WriteLine("No properties found.");
    }
    

提交回复
热议问题