. Net generic type conversion method,. net generic type

Source: Internet
Author: User

. 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 ));}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.