public static void EnsureColumnType <T>(DataRow dr, int rowindex, string columnname) { string colvalue = dr[columnname].ToString(); Type targetType = typeof(T); if (colvalue.Length == 0 && ValidationUtils.IsTheTargetTypeAValueTypeDifferentFromString(targetType)) { throw new Exception(string.Format("第[{0}]行的数据列'{1}'的值'{2}'不能转换为{3}", rowindex, columnname, colvalue, targetType)); } object convertedValue = null; try { TypeConverter typeConverter = TypeDescriptor.GetConverter(targetType); convertedValue = typeConverter.ConvertFromString(null, CultureInfo.CurrentCulture, colvalue); } catch { } string typename; if (targetType == typeof(int)) { typename = "整数"; } else if (targetType == typeof(bool)) { typename = "真假值"; } else if (targetType == typeof(decimal)) { typename = "小数"; } else if (targetType == typeof(DateTime)) { typename = "时间"; } else { typename = targetType.ToString(); } if (convertedValue == null) { throw new Exception(string.Format("第[{0}]行的数据列'{1}'的值'{2}'不能转换为{3}", rowindex, columnname, colvalue, typename)); } }