C#递归函数获取Sortable属性时父路径拼接错误求助
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:
- When processing
Profile.Client, you setparentPath = "Profile.Client" - Then when moving to
Profile.ProfileContact, you appended to this already modified path, resulting inProfile.Client.ProfileContact.Emailinstead of the correctProfile.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

