Expression Trees and PropertyDescriptor

531 views Asked by At

Is there any clean way to get a PropertyDescriptor from an expression tree?

I currently have PropertyInfo but I ideally want PropertyDescriptor, my code:

var prop = 
    (System.Reflection.PropertyInfo)
        ((MemberExpression)
            ((Expression<Func<TestClass, long>>)
                (p => p.ID)).Body).Member;

My need for PropertyDescriptor is because I need to use:

if (prop.CanResetValue(this))
{
    prop.ResetValue(this);
}
else
{
    prop.SetValue(this, null);
}

I cannot use PropertyInfo.SetValue(this, null, null) as it does not suit my needs, as I need to reset to the default value specified by the DefaultValueAttribute.

1

There are 1 answers

1
LukeH On BEST ANSWER

What about something like this? (Untested, sorry!)

var prop = /* same as in your example above */

var descriptors = TypeDescriptor.GetProperties(this);
var descriptor = descriptors[prop.Name];

if (descriptor.CanResetValue(this))
{
    descriptor.ResetValue(this);
}
else
{
    descriptor.SetValue(this, null);
}