2017-02-03 36 views
2

我有一個類的屬性作爲對象的任何更多的類。例如:如何重置PropertyGrid中組件屬性的默認值?

public Class Humans 
    { 
     public Person Human {get; set;} 

     [DefaulValue("New York")] 
     public string Sity {get; set;} 
    } 

    public struct Person 
    { 
     [DefaulValue("Name")] 
     public string Name {get; set;} 

     [DefaulValue("Surname")] 
     public string Surname {get; set;} 
    } 

如果我想重置人類類,我寫這篇文章:

PropertyDescriptorCollection props = TypeDescriptor.GetProperties(Humans); 
    foreach (PropertyDescriptor pr in props) 
    { 
     if (pr.Attributes.OfType<DefaultValueAttribute>().Any()) 
     { 
      pr.ResetValue(obj); 
     } 
    } 

在財產的情況下,一切都發生完全增寬,併爲人類的屬性沒有任何反應。那麼以下是如何重置爲這些屬性的默認值?

回答

0

您不需要檢查.Attributes。這裏的關鍵是pr.CanResetValue(obj)。如果返回true,則可以撥打pr.ResetValue(obj)。如果返回false,則不應該嘗試。具有支撐重置多種方法 - 包括:

  • [DefaultValue]
  • void Reset{membername}()
  • 定製PropertyDesciptor

我建議你嘗試添加:

void ResetHuman() { Human = null; } 

那麼你應該找到pr.CanResetValue(obj)返回truepr.ResetValue(obj)清除該值。

+0

事實是,我想使用重置方法的值不僅僅是一個類。因此,每個班級都需要添加一個方法Reset {membername}? – Nasay