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

C# 如何通过反射递归修剪对象及嵌套对象中所有字符串的前后空格

实现逻辑

你可以利用递归+集合类型判断,同时兼容嵌套自定义类、字符串集合两种场景的Trim处理,else分支补充逻辑如下:

else
{
    var propertyValue = property.GetValue(obj);
    if (propertyValue == null) continue;

    // 处理List<string>类型的tags
    if (property.PropertyType == typeof(List<string>))
    {
        var list = (List<string>)propertyValue;
        for (int i = 0; i < list.Count; i++)
        {
            if (!string.IsNullOrEmpty(list[i]))
            {
                list[i] = list[i].Trim();
            }
        }
    }
    // 处理嵌套自定义类,递归调用当前方法
    else if (property.PropertyType.IsClass)
    {
        // 反射获取泛型方法并调用,替换注释部分为你定义TrimWhiteSpaceOnRequest的类名
        var method = typeof(/* 替换为当前方法所在类的类名 */).GetMethod(nameof(TrimWhiteSpaceOnRequest), BindingFlags.NonPublic | BindingFlags.Static);
        var genericMethod = method.MakeGenericMethod(property.PropertyType);
        genericMethod.Invoke(null, new[] { propertyValue });
    }
}

另外原有代码存在两处需要修正的细节:

  • catch块中的field.getName()是Java语法,C#中应该替换为property.Name
  • 反射调用泛型方法时需要填写方法所属的类名,否则会获取不到方法实例

简化版实现(无需反射)

如果不想处理泛型反射的逻辑,可以把方法修改为非泛型版本,代码更简洁:

private static void TrimWhiteSpaceOnObject(object obj)
{
    if (obj == null) return;
    var type = obj.GetType();

    var properties = type.GetProperties();
    foreach (var property in properties)
    {
        try
        {
            if (property.PropertyType == typeof(string))
            {
                var val = property.GetValue(obj) as string ?? "";
                property.SetValue(obj, val.Trim());
            }
            else if (property.PropertyType == typeof(List<string>))
            {
                var list = property.GetValue(obj) as List<string>;
                if (list == null) continue;
                for (int i = 0; i < list.Count; i++)
                {
                    if (list[i] != null) list[i] = list[i].Trim();
                }
            }
            else if (property.PropertyType.IsClass && !property.PropertyType.Namespace.StartsWith("System"))
            {
                // 直接递归处理自定义类
                TrimWhiteSpaceOnObject(property.GetValue(obj));
            }
        }
        catch (Exception ex)
        {
            log.info("Error processing field " + property.Name);
        }
    }
}

调用时直接传入Request实例即可,会自动处理所有层级的字符串Trim需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 16:45:08