Skip to content

Instantly share code, notes, and snippets.

@jackinf
Created September 21, 2016 19:04
Show Gist options
  • Save jackinf/fc3629daac8644bfc3c04a1c493f6886 to your computer and use it in GitHub Desktop.
Save jackinf/fc3629daac8644bfc3c04a1c493f6886 to your computer and use it in GitHub Desktop.
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