/// <summary> /// 資料列轉換特定欄位 /// </summary> /// <param name="type"></param> /// <param name="dataRow"></param> /// <param name="columnName"></param> /// <returns></returns> public static object ConvertValue(this DataRow dataRow, Type type, string columnName) { var typeConverter = TypeDescriptor.GetConverter(type); try { return(typeConverter.ConvertFromString(dataRow[columnName].ToString())); } catch { var wrongTypeEx = new WrongTypeException(); wrongTypeEx.SourcePropertyType = dataRow[columnName].GetType(); wrongTypeEx.TargetPropertyType = type; throw wrongTypeEx; } }
/// <summary> /// 物件轉物件 /// </summary> /// <param name="source"></param> /// <param name="T"></param> /// <returns></returns> public static T ConvertValue <T>(this object source) { var targetType = typeof(T); var typeConverter = TypeDescriptor.GetConverter(targetType); try { return((T)typeConverter.ConvertFromString(source.ToString())); } catch { var wrongTypeEx = new WrongTypeException(); wrongTypeEx.SourcePropertyType = source.GetType(); wrongTypeEx.TargetPropertyType = targetType; throw wrongTypeEx; } }
/// <summary> /// 資料列轉換特定欄位 /// </summary> /// <param name="dataReader"></param> /// <param name="type"></param> /// <param name="columnName"></param> /// <returns></returns> public static object ConvertValue(this DbDataReader dataReader, Type type, string columnName) { var typeConverter = TypeDescriptor.GetConverter(type); var colIndex = dataReader.GetOrdinal(columnName); try { if (!dataReader.IsDBNull(colIndex)) { return(typeConverter.ConvertFromString(dataReader.GetValue(colIndex).ToString())); } } catch (FormatException ex) { var wrongTypeEx = new WrongTypeException(); wrongTypeEx.SourcePropertyType = dataReader.GetValue(colIndex).GetType(); wrongTypeEx.TargetPropertyType = type; throw wrongTypeEx; } return(null); }