指:Reflection - setting Type of returned obj? 我有一个名为 Call Jobcard 的对象,它具有一些属性,其中之一是另一个名为 Customer 的对象,它有自己的属性,其中之一是另一个名为 Adress 的嵌套对象。
这两个函数也将处理其他对象类型。
private T PopulateObject<T>(T dataObj, System.Data.DataRow dataRow)
{
//Type type = dataObj.GetType();
System.Reflection.PropertyInfo[] proplist = dataObj.GetType().GetProperties();
foreach ( System.Reflection.PropertyInfo propertyitem in proplist)
{
if(propertyitem.Name != "")
//s += propertyitem.Name + ":" + (propertyitem.GetValue(dataObj,null)).ToString() + "\r\n";
try
{
propertyitem.SetValue(dataObj, dataRow[propertyitem.Name], null);
}
catch (Exception ex)
{
if (ex.Message.Contains("does not belong to table"))
{
propertyitem.SetValue(dataObj, PopulateChildObject(propertyitem, dataRow), null);
}
else
throw;
}
}
return dataObj;
}
private object PopulateChildObject(object dataObj, System.Data.DataRow dataRow)
{
System.Reflection.PropertyInfo[] proplist = dataObj.GetType().GetProperties();
foreach ( System.Reflection.PropertyInfo propertyitem in proplist)
{
if(propertyitem.Name != "")
try
{
propertyitem.SetValue(dataObj, dataRow[propertyitem.Name], null);
}
catch (Exception ex)
{
if (ex.Message.Contains("does not belong to table"))
{
propertyitem.SetValue(dataObj, PopulateChildObject(propertyitem, dataRow), null);
}
else
throw;
}
}
return dataObj;
}
问题是 PopulateChildObject 函数不起作用,因为 PropertyInfo 列表不是传递的 childObj 的列表。 如果我查看 watch 中传递给 PopulateChildObject 的 dataObj,它有 0 个属性。此外,传递给 PopChildObj() 的 dataObj 具有 System.Reflection.RuntimePropertyInfo' 类型,而不是 Customer 类型。我错过了什么?
最佳答案
propertyitem
是 PropertyInfo
;您需要将属性中的值传递给它 - 即
propertyItem.GetValue(dataObj, null);
如果这个子对象是由父对象创建的,则不需要“设置”它;只需更新底层对象:
PopulateChildObject(propertyitem.GetValue(dataObj, null), dataRow);
您可能需要创建子对象(通常是Activator.CreateInstance
),在这种情况下您将需要调用设置值
:
object child = propertyitem.GetValue(dataObj, null);
if(child == null) {
child = Activator.CreateInstance(propertyitem.PropertyType);
propertyitem.SetValue(dataObj, child, null);
}
PopulateChildObject(child, dataRow);
但我想知道 - PopulateObject
和 PopulateChildObject
之间真的有什么区别吗?感觉它们可能是同一件事?
关于c# - 反射 - 获取嵌套对象的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/909777/