lundi 14 décembre 2015

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 .





Aucun commentaire:

Enregistrer un commentaire