You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过Reflection遍历对象,更新Employee及List<Employee>属性的值?

反射实现员工职位更新方案

完全可以通过反射实现你的需求,以下是具体的实现代码和说明:

核心逻辑步骤

  • 遍历EmployeesOfTheMonth对象的所有公开属性
  • 对每个属性做类型判断:
    • 若为Employee类型:检查JobTitleUpdated是否非空,若有值则覆盖JobTitle
    • 若为List<Employee>类型:遍历列表中的每个Employee实例,执行相同的职位更新逻辑
  • 处理反射过程中的类型转换和空值判断,避免异常

完整实现代码

using System;
using System.Collections.Generic;
using System.Reflection;

public class JobTitleUpdater
{
    public static void UpdateEmployeeJobTitles(EmployeesOfTheMonth employeesOfTheMonth)
    {
        if (employeesOfTheMonth == null)
            throw new ArgumentNullException(nameof(employeesOfTheMonth));

        // 获取EmployeesOfTheMonth类型的所有公开实例属性
        PropertyInfo[] properties = typeof(EmployeesOfTheMonth).GetProperties(BindingFlags.Public | BindingFlags.Instance);

        foreach (PropertyInfo prop in properties)
        {
            // 获取当前属性的值
            object propValue = prop.GetValue(employeesOfTheMonth);
            if (propValue == null)
                continue;

            // 处理单个Employee类型的属性
            if (prop.PropertyType == typeof(Employee))
            {
                UpdateSingleEmployeeJobTitle((Employee)propValue);
            }
            // 处理List<Employee>类型的属性
            else if (prop.PropertyType.IsGenericType && prop.PropertyType.GetGenericTypeDefinition() == typeof(List<>))
            {
                Type elementType = prop.PropertyType.GetGenericArguments()[0];
                if (elementType == typeof(Employee))
                {
                    var employeeList = (List<Employee>)propValue;
                    foreach (var emp in employeeList)
                    {
                        UpdateSingleEmployeeJobTitle(emp);
                    }
                }
            }
            // 其他类型属性直接跳过
            else
            {
                continue;
            }
        }
    }

    private static void UpdateSingleEmployeeJobTitle(Employee employee)
    {
        if (employee == null)
            return;

        // 仅当JobTitleUpdated不为空时更新JobTitle
        if (!string.IsNullOrEmpty(employee.JobTitleUpdated))
        {
            employee.JobTitle = employee.JobTitleUpdated;
            // 可选:更新后清空JobTitleUpdated字段
            // employee.JobTitleUpdated = null;
        }
    }
}

代码说明

  1. 属性遍历:使用GetProperties获取EmployeesOfTheMonth的所有公开实例属性,确保覆盖所有目标属性
  2. 类型判断:
    • 直接匹配Employee类型处理单个员工
    • 通过泛型类型定义判断是否为List<>,再验证元素类型是否为Employee
  3. 单个员工更新:提取独立方法UpdateSingleEmployeeJobTitle,复用逻辑并保持代码简洁
  4. 空值安全:全程加入空值判断,避免空引用异常

使用方式

只需调用静态方法即可完成所有员工的职位更新:

JobTitleUpdater.UpdateEmployeeJobTitles(employeesOfTheMonth);

内容的提问来源于stack exchange,提问作者PaulPerkins

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 12:40:53