Reputation: 185
I have a class with properties as objects any more classes. For example:
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;}
}
If I want to reset the Humans class, I write this:
PropertyDescriptorCollection props = TypeDescriptor.GetProperties(Humans);
foreach (PropertyDescriptor pr in props)
{
if (pr.Attributes.OfType<DefaultValueAttribute>().Any())
{
pr.ResetValue(obj);
}
}
In the case of property, everything happens perfectly Sity, and for properties Human nothing happens. So here's how to reset to the default values of these properties?
Upvotes: 2
Views: 1581
Reputation: 1062512
You don't need to check .Attributes
. The key here is pr.CanResetValue(obj)
. If that returns true
, you can call pr.ResetValue(obj)
. If it returns false
, you shouldn't try. There are multiple approaches for supporting resets - including:
[DefaultValue]
void Reset{membername}()
PropertyDesciptor
I suggest you try adding:
void ResetHuman() { Human = null; }
Then you should find that pr.CanResetValue(obj)
returns true
and pr.ResetValue(obj)
clears the value.
Upvotes: 1