由於數據類型多,要按照逐個類型寫一個類型轉換的方法的話一是代碼量多,顯得累贅。 ...
由於數據類型多,要按照逐個類型寫一個類型轉換的方法的話一是代碼量多,顯得累贅。
using System; using System.ComponentModel; using System.Globalization; /// <summary> /// 類型轉換 /// </summary> /// <param name="value">要轉換的值</param> /// <param name="destinationType">轉換的目標類型</param> /// <returns></returns> public static object To(object value, Type destinationType) { return To(value, destinationType, CultureInfo.InvariantCulture); } /// <summary> /// 類型轉換 /// </summary> /// <param name="value">要轉換的值</param> /// <param name="destinationType">轉換的目標類型</param> /// <param name="culture">區域信息</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.CanConvertTo(destinationType)) return sourceConverter.ConvertTo(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> /// 類型轉換 /// </summary> /// <typeparam name="T">目標類型</typeparam> /// <param name="value">要轉換的值</param> /// <returns></returns> public static T To<T>(object value) { return (T)To(value, typeof(T)); }