C# DataRow转成类实体<T>扩展函数

213 阅读1分钟
public static class ExtensionMethods{
	/// <summary>
	/// DataRow转成类实体<T>
	/// </summary>
	/// <typeparam name="T"></typeparam>
	/// <param name="row"></param>
	/// <returns></returns>
	public static T ToObject<T>(this DataRow row) where T : class
	{
		DataColumnCollection columns = row.Table.Columns;
		Type type = typeof(T);
		var plist = new List<PropertyInfo>(type.GetProperties());
		var flist = new List<FieldInfo>(type.GetFields());
		T rowData = Activator.CreateInstance<T>();
		foreach (DataColumn dc in columns)
		{
			PropertyInfo pInfo = plist.Find(p => p.Name == dc.ColumnName);
			if (pInfo != null)
			{
				try
				{
					var pValue = row[dc.ColumnName];
					if (!Convert.IsDBNull(pValue))
					{
						object pVal = null;
						if (pInfo.PropertyType.ToString().Contains("System.Nullable"))
						{
							pVal = Convert.ChangeType(pValue, Nullable.GetUnderlyingType(pInfo.PropertyType));
						}
						else
						{
							pVal = Convert.ChangeType(pValue, pInfo.PropertyType);
						}
						pInfo.SetValue(rowData, pVal);
					}
				}
				catch (Exception ex)
				{
					throw new Exception("属性[" + pInfo.Name + "]转换出错," + ex.Message, ex);
				}
			}
			FieldInfo fInfo = flist.Find(f => f.Name == dc.ColumnName);
			if (fInfo != null)
			{
				try
				{
					var fValue = row[dc.ColumnName];
					if (!Convert.IsDBNull(fValue))
					{
						object fVal = null;
						if (fInfo.FieldType.ToString().Contains("System.Nullable"))
						{
							fVal = Convert.ChangeType(fValue, Nullable.GetUnderlyingType(fInfo.FieldType));
						}
						else
						{
							fVal = Convert.ChangeType(fValue, fInfo.FieldType);
						}
						fInfo.SetValue(rowData, fVal);
					}
				}
				catch (Exception ex)
				{
					throw new Exception("字段[" + fInfo.Name + "]转换出错," + ex.Message, ex);
				}
			}
		}
		return rowData;
	}
}