Created
September 21, 2016 19:04
-
-
Save jackinf/fc3629daac8644bfc3c04a1c493f6886 to your computer and use it in GitHub Desktop.
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.Linq.Expressions; | |
using System.Reflection; | |
namespace Playground | |
{ | |
public class Attr : Attribute | |
{ | |
private int v; | |
public Attr(int v) | |
{ | |
this.v = v; | |
} | |
} | |
public class Base | |
{ | |
[Attr(1)] | |
public virtual string Bar { get; set; } | |
} | |
public class Child : Base | |
{ | |
[Attr(1)] | |
public override string Bar { get; set; } | |
} | |
public static class PropertyHelper<T> | |
{ | |
public static PropertyInfo GetProperty<TValue>( | |
Expression<Func<T, TValue>> selector) | |
{ | |
Expression body = selector; | |
if (body is LambdaExpression) | |
{ | |
body = ((LambdaExpression)body).Body; | |
} | |
switch (body.NodeType) | |
{ | |
case ExpressionType.MemberAccess: | |
return (PropertyInfo)((MemberExpression)body).Member; | |
default: | |
throw new InvalidOperationException(); | |
} | |
} | |
} | |
class Program | |
{ | |
public static void Main() | |
{ | |
PropertyInfo prop = PropertyHelper<Child>.GetProperty(x => x.Bar); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment