使用Reflection填充自定义类属性

时间:2015-12-14 12:19:02

标签: c# reflection

首先,我是反思的新手。我创建了课程:

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的扩展方法。 缺什么 ? 谢谢。

1 个答案:

答案 0 :(得分:5)

GetProperty是Type类的一个方法。

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