我正在尝试编写一个非常松散的耦合方法来映射从数据库返回的值,并将其存储在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
总是返回null
为pi.GetValue(currentClass, null)
。我也尝试过pi.GetGetMethod().Invoke(currentClass, null)
,但是它也返回null。任何帮助将不胜感激,谢谢!
编辑:所有在这里讨论的性质是形式的自动属性:
public ComplexType theProperty { get; private set; }
是已经创建的子对象,还是需要先实例化它们? – Locksfree 2012-03-23 16:04:05
这发生在父对象的原始实例化过程中,因此需要对子对象进行实例化以及分配。 – 2012-03-23 16:45:58