2015-12-14 71 views
3

首先,我是新来的反思。我创建的类:使用反射填充自定义类属性

using System.Reflection; 

public class EmployeeInfo 
{ 
    public string EmployeeName { get; set; } 
    public string PhoneNumber { get; set; } 
    public string Office { get; set; } 
    public string Department { get; set; } 
    public string Position { get; set; } 
    public string PhoneType { get; set; } 
    public bool IsPublic { get; set; } 

} 

现在我试图开发将使用一些商业逻辑填充所有属性的方法(如果为空则空字符串等)通过反射,并返回的EmployeeInfo列表。我认为应该是这个样子:

public List<Models.EmployeeInfo> GetEmployeeInfo(SPListItemCollection splic) 
    { 

     var listEmployeeInfo = new List<Models.EmployeeInfo>(); 
     var propertyNames = new List<string>() {"EmployeeName","Position","Office","IsPublic"}; 

     foreach (SPListItem item in splic) 
     { 
      var employeeInfo = new Models.EmployeeInfo(); 


      foreach (var propertyName in propertyNames) 
      { 
       string newData = ""; 
       if (item[propertyName] != null) 
       { 
        newData = item[propertyName].ToString(); 
       } 
       employeeInfo.GetProperty(propertyName).SetValue(employeeInfo, newData, null); 

      } 
      listEmployeeInfo.Add(employeeInfo); 
     } 

     return listEmployeeInfo; 


    } 

但我不能在这行叫GetPropertySetValue扩展方法:

employeeInfo.GetProperty(propertyName).SetValue(employeeInfo, newData, null); 

错误信息说我的Models.EmployeeInfo类不包含定义对于GetProperty和没有扩展方法GetProperty。 缺什么? 谢谢。

+0

我在代码审查网站上提出了同样的问题。我有一些非常好的评论意见来做到这一点。你可以在这里检查问题http://codereview.stackexchange.com/questions/102289/setting-the-value-of-properties-via-reflection – Sandeep

回答

3

GetProperty是Type类的方法。

employeeInfo.GetType().GetProperty(propertyName).SetValue(employeeInfo, newData, null); 
+0

谢谢安迪,我试过这个,但我得到“未将对象引用设置为对象的实例” –

+0

您需要调试代码。设置一个中断点,并且为每一步考虑你认为应该发生的事情,然后观察实际发生的事情。我怀疑GetProperty会由于某种原因返回null,但这就是您将在调试中发现的内容。 – AndyJ

+0

找到了bug。谢谢! –