2011-11-01 71 views
1

是否有任何干淨的方法從表達式樹中獲取PropertyDescriptor表達式樹和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指定的默認值。

回答

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

優雅而簡單,由於某種原因,智能感知告訴我,'PropertyDescriptorCollection'只能用'int'指數工作不'string',重置VS2010似乎已經解決了這一點。 – Seph