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

前端 未结 2 1304
猫巷女王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:01

    Yes, you'll be able to see everything directly referenced. Of course, if someone passes

    x => ComputeAge(x) > 18
    

    then you won't necessarily know that ComputeAge refers to the Age property.

    The expression tree will be an accurate representation of exactly what's in the lambda expression.

    0 讨论(0)
  • 2021-01-16 11:18

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

    public class PropertyAccessFinder : ExpressionVisitor {
        private readonly HashSet<PropertyInfo> _properties = new HashSet<PropertyInfo>();
    
        public IEnumerable<PropertyInfo> 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);
    
    0 讨论(0)
提交回复
热议问题