samedi 17 décembre 2022

Using Reflection to Iterate and update value of an object for specific property types

I have an object, employeesOfTheMonth of type EmployeesOfTheMonth, which contains a number of properties of types Employee as well as List<Employee>. In some instances, the value of a given employee's JobTitleUpdated field contains an updated job title; in other instances, the JobTitleUpdated field is null.

    public class Employee
    {
        public int EmployeeId {get; set; }
        public string EmployeeName { get; set;}
        public string? JobTitle { get; set; }
        public string? JobTitleUpdated { get; set;}
        public decimal Salary { get; set; }
        public byte[] Photo { get; set; }
    }

    public class EmployeesOfTheMonth
    {   
        public string Company
        public Employee EmployeeOfTheMonthLocation1 {get; set;}
        public Employee EmployeeOfTheMonthLocation2 {get ;set;}
        public Employee EmployeeOfTheMonthLocation3 {get; set;}
        public List<Employee> EmployeesOfPriorMonthsLocation1 {get; set;}
        public List<Employee> EmployeesOfPriorMonthsLocation2 {get; set;}
        public List<Employee> EmployeesOfPriorMonthsLocation3 {get; set;}
        public DateTime ModifiedDate { get; set; }
        [... additional properties of various types snipped...]
    }

Using Reflection, I would like to iterate the properties of employeesOfTheMonth. If the property is of type Employee and if the JobTitleUpdated property of a given Employee contains data, I need to update the value of the JobTitle of the Employee with the value of the JobTitleUpdated property. In the case of List<Employee>, I need to iterate through that list and apply the same logic, namely conditionally updating the JobTitle with the JobTitleUpdated property.

Can this be done via Reflection?





Aucun commentaire:

Enregistrer un commentaire