【发布时间】:2012-03-24 01:09:48
【问题描述】:
我正在尝试编写一个非常松散耦合的方法来将从数据库返回并存储在DataTable 中的值映射到自定义对象的属性。这适用于所有值类型属性,但我无法设置本身是主类属性的对象的属性。这是我目前所拥有的:
protected void AssignDataRowToFields(DataRow data, object currentClass = null)
{
string strPrefix = currentClass == null ? string.Empty : currentClass.GetType().Name;
currentClass = currentClass ?? this;
PropertyInfo[] properties = currentClass.GetType().GetProperties();
foreach (PropertyInfo pi in properties)
{
if (pi.PropertyType.IsValueType || typeof(string).IsAssignableFrom(pi.PropertyType))
{
if (typeof(string).IsAssignableFrom(pi.PropertyType))
pi.SetValue(this, data[strPrefix + pi.Name].ToString(), null);
else if (typeof(int).IsAssignableFrom(pi.PropertyType))
pi.SetValue(this, int.Parse(data[strPrefix + pi.Name].ToString()), null);
}
else
this.AssignDataRowToFields(data, pi.GetValue(currentClass, null));
}
}
我递归调用AssignDataRowToFields 的最后一个else 总是为pi.GetValue(currentClass, null) 返回null。我也试过pi.GetGetMethod().Invoke(currentClass, null),但这也返回null。任何帮助将不胜感激,谢谢!
编辑:这里讨论的所有属性都是表单的自动属性:
public ComplexType theProperty { get; private set; }
【问题讨论】:
-
子对象是已经创建了还是需要先实例化?
-
这发生在父对象的原始实例化过程中,因此子对象需要实例化和分配。
标签: c#-4.0 reflection recursion