简体   繁体   English

使用反射填充自定义类属性

[英]Populating custom class properties using Reflection

First of all , I'm new to reflection . 首先,我是新手。 I've created class : 我创建了课程:

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

}

Now I'm trying to develop a method that will populate all the properties using some business logic (if null then empty string etc) via reflection, and returning a list of EmployeeInfo . 现在,我正在尝试开发一种方法,该方法将通过反射使用一些业务逻辑(如果为null,然后为空字符串等)填充所有属性,并返回EmployeeInfo列表。 I thought it should look something like this : 我认为它应该看起来像这样:

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;


    }

But I can't call GetProperty or SetValue extension methods at this line : 但是我不能在这一行调用GetPropertySetValue扩展方法:

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

Error Message says that my Models.EmployeeInfo class doesn't contain definition for GetProperty and no extension method GetProperty . 错误消息说我的Models.EmployeeInfo类不包含GetProperty定义,也没有扩展方法GetProperty What is missing ? 缺什么 ? Thank you . 谢谢 。

GetProperty是Type类上的方法。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM