.NET 数据单行转换为单个T类

public static (T Data, string Error) DataRowToClass<T>(DataRow dr)
{
T obj = Activator.CreateInstance<T>(); //活化剂类实例化泛型对象
string strError = "";
if (dr != null)
{
#region
try
{

#region

//赋值
var cProperties = typeof(T).GetProperties();
foreach (var proper in cProperties)
{
if (
proper.PropertyType == typeof(string)
|| proper.PropertyType == typeof(long?)
|| proper.PropertyType == typeof(DateTime?)
|| proper.PropertyType == typeof(decimal?)
)
{

if (dr.Table.Columns.Contains(proper.Name))
{
#region 存在列名
//仅处理4种类型
if (proper.PropertyType == typeof(string))
{
proper.SetValue(obj, clsBase.ObjectToString(dr[proper.Name]));
}
if (proper.PropertyType == typeof(long?))
{
proper.SetValue(obj, clsBase.StrToLong(clsBase.ObjectToString(dr[proper.Name])));
}
if (proper.PropertyType == typeof(DateTime?))
{
proper.SetValue(obj, clsBase.StrToDateTime(clsBase.ObjectToString(dr[proper.Name])));
}
if (proper.PropertyType == typeof(decimal?))
{
proper.SetValue(obj, clsBase.StrToDecimal(clsBase.ObjectToString(dr[proper.Name])));
}
//其它类型暂不处理
#endregion
}
else
{
#region 不存在列名

strError += "列名[" + proper.Name + "]不存在;";

#endregion
}

}
else
{
//非处理类型不处理
}


}
#endregion

}
catch (Exception ex)
{
strError += ex.Message;
}

#endregion
}

if (!string.IsNullOrWhiteSpace(strError))
{
strError = "FullClassName[" + typeof(T).FullName + "];" + strError;
}
return (obj, strError);
}

posted @ 2022-07-04 17:42  御翼仁粨狩  阅读(39)  评论(0)    收藏  举报