Currently, i have a declaration in a root class that iterates through the properties of a deriving class and instantiates the Default Value of the property, using the DefaultValueAttribute descriptor. What i want to do is expand this from simply being for DefaultValue to also be XmlElement, XmlAttribute and the series of Attributes included in the Serialization of the Xml namespace.
I am having a problem with expanding the current design to handle multiple attributes without loading a ton of if/then/else statements to handle the various Defined Attributes.
Current Design:
private void Initialize () {
foreach( PropertyDescriptor property in TypeDescriptor.GetProperties( this ) ) {
XmlElementAttribute xel = ( XmlElementAttribute ) property.Attributes[typeof( XmlElementAttribute )];
if( xel != null ) {
this.AddElement( xel.ElementName , "" );
}
DefaultValueAttribute attr = ( DefaultValueAttribute ) property.Attributes[typeof( DefaultValueAttribute )];
if( attr != null ) {
property.SetValue( this , attr.Value );
}
}
}
Suggestions Design:
private void Initialize () {
foreach( PropertyDescriptor property in TypeDescriptor.GetProperties( this ) ) {
foreach( Attribute attr in property.Attributes ) {
if( attr = typeof(XmlElementAttribute)){
//do something
}else if(attr = typeof(DefaultValueAttribute)){
//do something
}
}
}
}
You could define a
Dictionary<Type, Action<object>>(or replaceobjectwith the specific type of your class) and add the code you want to execute for each type:Now you can just test whether your dictionary contains the type and execute the delegate: