mardi 14 juillet 2015

Converting 'anything' to string via TypeConverters

I'm trying to create an utility method which converts a value of any arbitary type to another type using a TypeConverter. However, when trying to convert something to string, the TypeConverter always fails.

private bool TryConvertType(object value, Type targetType, out object result) {
    result = null;
    if(value == null)
        return false;

    try {

        if(targetType.IsInstanceOfType(value)) {
            result = value;
            return true;
        }

        var typeConverter = TypeDescriptor.GetConverter(targetType);
        if(typeConverter.CanConvertFrom(value.GetType())) {
            result = typeConverter.ConvertFrom(value);
            return true;
        }
        ...

Given the value as type bool and the targetType string, the method .CanConvertFrom() always returns false. Why shouldn't it be possible to create a string from a boolean value? Or am I missing something here?





Aucun commentaire:

Enregistrer un commentaire