. Net generic type conversion method,. net generic type
Because there are many data types, it is cumbersome to write a type conversion method based on each type.
Using System; using System. componentModel; using System. globalization; /// <summary> // type conversion // </summary> /// <param name = "value"> value to be converted </param> /// <param name = "destinationType"> conversion target type </param> // <returns> </returns> public static object To (object value, type destinationType) {return To (value, destinationType, CultureInfo. invariantCulture);} // <summary> // type conversion // </summary> // <param name = "value"> Value </param> /// <param name = "destinationType"> destination type of the conversion </param> /// <param name = "culture"> region Information </param >/// <returns> </returns> public static object To (object value, type destinationType, CultureInfo culture) {if (value! = Null) {var sourceType = value. GetType (); var destinationConverter = TypeDescriptor. GetConverter (destinationType); if (destinationConverter! = Null & destinationConverter. canConvertFrom (value. getType () return destinationConverter. convertFrom (null, culture, value); var sourceConverter = TypeDescriptor. getConverter (sourceType); if (sourceConverter! = Null & sourceConverter. canconverconverter (destinationType) return sourceConverter. convertize (null, culture, value, destinationType); if (destinationType. isEnum & value is int) return Enum. toObject (destinationType, (int) value); if (! DestinationType. isInstanceOfType (value) return Convert. changeType (value, destinationType, culture);} return value ;} /// <summary> /// type conversion /// </summary> /// <typeparam name = "T"> target type </typeparam> /// <param name = "value"> value To be converted </param> // <returns> </returns> public static T To <T> (object value) {return (T) To (value, typeof (T ));}