PropertyInfo from Delegate

2019-07-19 14:35发布

问题:

Is there a simple way to get the PropertyInfo for a property in a delegate, assuming it is a simple property seletor?

Example:

var propertyInfo = Method<MyClass,int>(s => s.Property);

...

PropertyInfo Method(Func<T1,T2> selector)
{
   // What goes here?
}

回答1:

Using Expression you can:

    static PropertyInfo ExtractProperty<T>(Expression<Func<T>> selector)
    {
        return (selector.Body as MemberExpression).Member as PropertyInfo;
    }