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

C#递归函数获取Sortable属性时父路径拼接错误求助

Fixing Path Concatenation Issue in Recursive Sortable Property Retrieval

Let's fix that path concatenation bug you're hitting. The core problem here is that when processing multiple [NestedSortable] properties in the same class, your original recursive logic was reusing and modifying the same path variable across calls—causing the path from the first nested property to bleed into the second one.

Corrected Recursive Function

public static List<string> GetTermsFromModel(Type modelType, string parentPath)
{
    var terms = new List<string>();

    // Collect all directly sortable properties
    var sortableProps = modelType.GetProperties()
        .Where(p => Attribute.IsDefined(p, typeof(SortableAttribute)));
    
    foreach (var prop in sortableProps)
    {
        var fullPath = string.IsNullOrEmpty(parentPath) 
            ? prop.Name 
            : $"{parentPath}.{prop.Name}";
        terms.Add(fullPath);
    }

    // Process each nested sortable property independently
    var nestedProps = modelType.GetProperties()
        .Where(p => Attribute.IsDefined(p, typeof(NestedSortableAttribute)));
    
    foreach (var prop in nestedProps)
    {
        // Create a unique path for THIS nested property (based on original parent path)
        var currentNestedPath = string.IsNullOrEmpty(parentPath)
            ? prop.Name
            : $"{parentPath}.{prop.Name}";
        
        // Recurse with the isolated path, not a modified shared variable
        var nestedTerms = GetTermsFromModel(prop.PropertyType, currentNestedPath);
        terms.AddRange(nestedTerms);
    }

    return terms;
}

Why Your Original Code Failed

In your initial implementation, you were probably updating the parentPath variable in-place for each nested property. For example:

  1. When processing Profile.Client, you set parentPath = "Profile.Client"
  2. Then when moving to Profile.ProfileContact, you appended to this already modified path, resulting in Profile.Client.ProfileContact.Email instead of the correct Profile.ProfileContact.Email

The fix ensures each nested property gets its own independent path string, built from the original parent path (not the altered one from a sibling nested property). This isolates each recursive call and prevents cross-contamination between sibling nested properties.

Expected Output After Fix

When you run var declaredTerms = GetTermsFromModel(typeof(User), null);, you'll get the exact list you wanted:

  • FirstName
  • LastName
  • Profile.BrandName
  • Profile.Client.Name
  • Profile.ProfileContact.Email

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.13 09:04:08