【问题标题】:Expression Trees and PropertyDescriptor表达式树和 PropertyDescriptor
【发布时间】:2011-11-01 13:30:40
【问题描述】:

有什么干净的方法可以从表达式树中获取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指定的默认值。

【问题讨论】:

    标签: c# .net expression-trees typedescriptor propertydescriptor


    【解决方案1】:

    这样的事情呢? (未经测试,抱歉!)

    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);
    }
    

    【讨论】:

    • 又好又简单,由于某种原因,intellisense 告诉我 PropertyDescriptorCollection 只适用于 int 索引而不是 string,重置 VS2010 似乎已经解决了这个问题。
    猜你喜欢
    • 1970-01-01
    • 2010-12-07
    • 2013-02-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-14
    相关资源
    最近更新 更多