1

有什么干净的方法可以PropertyDescriptor从表达式树中获取一个?

我目前有PropertyInfo,但理想情况下我想要PropertyDescriptor我的代码:

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

我需要 PropertyDescriptor 是因为我需要使用:

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

我不能使用PropertyInfo.SetValue(this, null, null),因为它不适合我的需要,因为我需要重置为DefaultValueAttribute.

4

1 回答 1

2

这样的事情呢?(未经测试,对不起!)

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);
}
于 2011-11-01T13:47:52.523 回答