C#利用反射简化给类字段赋值
2012-12-05 14:33:38 来源:WEB开发网核心提示:Type oType = Type.GetType("CCB_Donet.ClassFolder.FieldRuleInfo");//生成类对象数组,和数据库记录个数是一致的mMainFieldRule = new FieldRuleInfo[dtGet.Rows.Count];
Type oType = Type.GetType("CCB_Donet.ClassFolder.FieldRuleInfo");
//生成类对象数组,和数据库记录个数是一致的
mMainFieldRule = new FieldRuleInfo[dtGet.Rows.Count];
for (int i = 0; i < dtGet.Rows.Count; i++)
{
//这里使用反射动态为FieldRuleInfo字段赋值数据
mMainFieldRule[i] = new FieldRuleInfo();
for (int j = 0; j < dtGet.Columns.Count; j++)
{
//这里直接获取类的字段名称,然后把数据库里对应字段的值赋值给它
FieldInfo fieldInfo = oType.GetField("gStr" + dtGet.Columns[j].ColumnName,
BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance
| BindingFlags.Static);
fieldInfo.SetValue(mMainFieldRule[i], dtGet.Rows[i][j].ToString());
}
}
return true;
#if(DEBUG)
}
catch (Exception ex)
{
return false;
MyLog.WriteErrLog("frmDE-m_GetRule", ex.Message);
}
finally
{
dtGet = null;
}
#endif
}
#endregion
更多精彩
赞助商链接