Last active
August 29, 2015 14:04
-
-
Save jwChung/32077c4a670165d87a2d to your computer and use it in GitHub Desktop.
ExpressionVisitor demo
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Linq.Expressions; | |
using System.Reflection; | |
using Xunit; | |
namespace ClassLibrary1 | |
{ | |
public class CollectingPropertiesTest | |
{ | |
[Fact] | |
public void VisitCollectsProperties() | |
{ | |
// Fixture setup | |
var sut = new CollectingProperties(); | |
Expression<Func<Person, string>> nameExpr = x => x.Name; | |
Expression<Func<Person, int>> ageExpr = x => x.Age; | |
// Exercise system | |
sut.Visit(nameExpr); | |
sut.Visit(ageExpr); | |
// Verify outcome | |
Assert.Equal(2, sut.Properties.Count); | |
Assert.Equal(typeof(Person).GetProperty("Name"), sut.Properties[0]); | |
Assert.Equal(typeof(Person).GetProperty("Age"), sut.Properties[1]); | |
} | |
public class Person | |
{ | |
public string Name { get; set; } | |
public int Age { get; set; } | |
} | |
} | |
public class CollectingProperties : ExpressionVisitor | |
{ | |
private List<PropertyInfo> properties = new List<PropertyInfo>(); | |
public IList<PropertyInfo> Properties | |
{ | |
get { return this.properties; } | |
} | |
protected override Expression VisitMember(MemberExpression node) | |
{ | |
var property = node.Member as PropertyInfo; | |
if (property != null) | |
this.properties.Add(property); | |
return base.VisitMember(node); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment