pea*_*ace 3 .net c# vb.net reflection
foreach (PropertyInfo PropertyItem in this.GetType().GetProperties())
{
PropertyItem.SetValue(this, objDataTable.Rows[0][PropertyItem.Name.ToString()], null);
}
Run Code Online (Sandbox Code Playgroud)
在其中一个循环中,我得到了这个特殊的错误:
"System.DBNull"类型的对象无法转换为"System.String"类型.
发生此错误是因为数据库中的某个字段没有值(null),因此字符串属性无法处理它.如何将此null转换为字符串?
如果您知道更短或更好的一个,请随意发布.我试图避免检查每个循环当前值是否为null.
Ben得到它几乎是正确的(我实际上认为这只是他身边的一个"错字",但我不能为他编辑).这应该可以解决问题.
foreach (PropertyInfo PropertyItem in this.GetType().GetProperties())
{
var value = objDataTable.Rows[0][PropertyItem.Name.ToString()];
PropertyItem.SetValue(this, value == DBNull.Value ? "" : value.ToString() , null);
}
Run Code Online (Sandbox Code Playgroud)
并且你需要测试每次迭代,因为它是给定行中给定单元格中的值,实际上没有办法避免在使用它们之前检查每个单元格值