Can I use Expression> and reliably see which properties are referenced in the Func?

前端 未结 2 1303
猫巷女王i
猫巷女王i 2021-01-16 10:49

I\'m writing something in the flavour of Enumerable.Where in that takes a predicate of the form Func. If the underlying T

2条回答
  •  爱一瞬间的悲伤
    2021-01-16 11:18

    Small code example of a visitor that would find directly referenced properties.

    public class PropertyAccessFinder : ExpressionVisitor {
        private readonly HashSet _properties = new HashSet();
    
        public IEnumerable Properties {
            get { return _properties; }
        }
    
        protected override Expression VisitMember(MemberExpression node) {
            var property = node.Member as PropertyInfo;
            if (property != null)
                _properties.Add(property);
    
            return base.VisitMember(node);
        }
    }
    
    // Usage:
    var visitor = new PropertyAccessFinder();
    visitor.Visit(predicate);
    foreach(var prop in visitor.Properties)
        Console.WriteLine(prop.Name);
    

提交回复
热议问题