mercredi 24 juin 2015

Check if a type converter is available?

I need to 'serialize' and 'deserialize' certain complex types into custom formatted strings and for this, I'm looping through the properties of each type while applying the following rules:

  • If a property type is a special type, convert it into a string and 'save'.
  • If a property is a complex type, loop through that type again.

Now, what exactly is a special type? One of the following conditions should be met:

  • The type is a value type (.IsValueType)
  • The type is string
  • There's a type converter registered for that type (a client has the ability to register custom type converters if no default one is available).

The last part is where I have no clue on how to check this. As soon as I check for something like TypeDescriptor.GetConverter(type) != null, the condition is always true, even if it's a complex type - and so further properties aren't being looped through.

Pseudo code:

#binding
void bindModelProperty(prefix, parent, propertyInfo)
    if(isSpecialType(propertyInfo.PropertyType)) 
        rawValue = getValueFromDict(key)
        if(isEmpty || !TryConvertType(propertyType, out value))
            value = GetDefaultValue()

        propertyInfo.SetValue(parent, value)
        continue

    model = GetDefaultInstanceOfComplexType()
    BindModelProperties(key, model, propertyType)

isSpecialType(type)
    type.IsValueType || type == typeof(string) || TypeDescriptor.GetConverter() != null





Aucun commentaire:

Enregistrer un commentaire