How to lookup and invoke a .Net TypeConverter for a particular type?

前端 未结 4 633
后悔当初
后悔当初 2020-12-28 22:06

I would like to implement a general purpose runtime type conversion function that makes use .Net TypeConverters to do the conversion.

Does anyone know how to how t

4条回答
  •  無奈伤痛
    2020-12-28 22:13

        TypeConverter converter = TypeDescriptor.GetConverter(sourceType);
        if(converter.CanConvertTo(destinationType)) {
            return converter.ConvertTo(obj, destinationType);   
        }
        converter = TypeDescriptor.GetConverter(destinationType);
        if(converter.CanConvertFrom(sourceType)) {
            return converter.ConvertFrom(obj);
        }
    

    You could also look at Convert.ChangeType(obj, destinationType)

提交回复
热议问题