利用反射给实体动态赋值麻烦帮忙解释下
请各位大侠帮忙看看我从网上查资料在自己写写弄出来了,但好多代码还不不太明白,还请帮忙注释解释下每句代码什么意思,写写各位先。
/// <summary>
/// 利用反射根据DataReader和实体对象动态为实体赋值
/// </summary>
/// <param name="reader">数据源DataReader</param>
/// <param name="targetObj">实体对象</param>
private void GetReaderToObject(IDataReader reader, object targetObj)
{
for (int i = 0; i < reader.FieldCount; i++)
{
string columnName = reader.GetName(i);
object columnValue = reader.GetValue(i);
PropertyInfo property = targetObj.GetType().GetProperty(columnName);
if (property != null)
{
if (columnValue != DBNull.Value)
{
if (property.PropertyType.IsEnum)
{
object enumName = Enum.ToObject(property.PropertyType, columnValue);
property.SetValue(targetObj, enumName, null);
}
else
{
property.SetValue(targetObj, columnValue, null);
}
}
}
}
}