【问题标题】:Populating custom class properties using Reflection使用反射填充自定义类属性
【发布时间】:2015-12-14 12:19:01
【问题描述】:

首先,我是反射新手。我已经创建了类:

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; }

}

现在我正在尝试开发一种方法,该方法将使用一些业务逻辑(如果为 null,则为空字符串等)通过反射填充所有属性,并返回 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 。 缺什么 ? 谢谢。

【问题讨论】:

标签: c# reflection


【解决方案1】:

GetProperty 是 Type 类的一个方法。

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

【讨论】:

  • 谢谢安迪,我试过这个,但我得到“对象引用未设置为对象的实例”
  • 你需要调试你的代码。设置一个断点,为每一步思考你认为应该发生的事情,然后观察实际发生的事情。我怀疑 GetProperty 会出于某种原因返回 null,但这就是您在调试时会发现的。
  • 发现错误。谢谢!
猜你喜欢
  • 1970-01-01
  • 2017-05-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-04-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多