2012-03-23 59 views
1

我正在尝试编写一个非常松散的耦合方法来映射从数据库返回的值,并将其存储在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总是返回nullpi.GetValue(currentClass, null)。我也尝试过pi.GetGetMethod().Invoke(currentClass, null),但是它也返回null。任何帮助将不胜感激,谢谢!

编辑:所有在这里讨论的性质是形式的自动属性:

public ComplexType theProperty { get; private set; } 
+0

是已经创建的子对象,还是需要先实例化它们? – Locksfree 2012-03-23 16:04:05

+0

这发生在父对象的原始实例化过程中,因此需要对子对象进行实例化以及分配。 – 2012-03-23 16:45:58

回答

1

确保您的类构造函数首先创建的子对象。

+0

这个伎俩。 – 2012-03-23 18:26:13