fork(1) download
  1. using System;
  2. using System.Linq.Expressions;
  3. using System.Reflection;
  4.  
  5. public class Test
  6. {
  7. private object Foo { get; }
  8. private object Bar { get; }
  9.  
  10. static void MyMethod(params Expression<Func<Test,object>>[] fields) {
  11. foreach (var fieldExpr in fields) {
  12. var finder = new Finder("Foo");
  13. finder.Visit(fieldExpr);
  14. if (finder.IsFound) {
  15. Console.WriteLine("Expression {0} reference 'Foo'", fieldExpr);
  16. } else {
  17. Console.WriteLine("Expression {0} does not reference 'Foo'", fieldExpr);
  18. }
  19. }
  20. }
  21.  
  22. static void Main(string[] args) {
  23. MyMethod(e => e.Foo, e => e.Bar, e => e.Bar != null ? e.Foo : e.Bar);
  24. }
  25. }
  26.  
  27.  
  28. internal class Finder : ExpressionVisitor {
  29. private readonly string toFind;
  30.  
  31. public Finder(string toFind) {
  32. this.toFind = toFind;
  33. }
  34.  
  35. public bool IsFound { get; private set; }
  36.  
  37. protected override Expression VisitMember(MemberExpression node) {
  38. IsFound |= node.Member.MemberType == MemberTypes.Property && node.Member.Name == toFind;
  39. return base.VisitMember(node);
  40. }
  41. }
  42.  
Success #stdin #stdout 0.02s 132672KB
stdin
Standard input is empty
stdout
Expression e => e.Foo reference 'Foo'
Expression e => e.Bar does not reference 'Foo'
Expression e => IIF((e.Bar != null), e.Foo, e.Bar) reference 'Foo'