Question

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.

Was it helpful?

Solution

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);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top