首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >表达式树和PropertyDescriptor

表达式树和PropertyDescriptor
EN

Stack Overflow用户
提问于 2011-11-01 21:30:41
回答 1查看 501关注 0票数 1

有没有从表达式树中获取PropertyDescriptor的干净方法?

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

代码语言:javascript
复制
var prop = 
    (System.Reflection.PropertyInfo)
        ((MemberExpression)
            ((Expression<Func<TestClass, long>>)
                (p => p.ID)).Body).Member;

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

代码语言:javascript
复制
if (prop.CanResetValue(this))
{
    prop.ResetValue(this);
}
else
{
    prop.SetValue(this, null);
}

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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2011-11-01 21:47:53

像这样的怎么样?(未经测试,抱歉!)

代码语言:javascript
复制
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);
}
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/7967214

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档