简体   繁体   中英

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 . 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 :

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 . What is missing ? Thank you .

GetProperty是Type类上的方法。

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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