如何获取嵌套类的属性值?C#嵌套类属性提取需求
Solution to Extract Nested Class Properties
To modify your GetPrimitiveProperties method to support nested objects, we need to add recursive logic to traverse complex types while avoiding infinite recursion (critical for self-referential classes like Category with CategoryFather). Here's the updated implementation:
Modified Code
public static List<DataPropertyReport> GetPrimitiveProperties<T>(T entity) { // Initialize visited set to prevent infinite loops and empty property path prefix return GetPrimitiveProperties(entity, new HashSet<object>(), string.Empty); } private static List<DataPropertyReport> GetPrimitiveProperties(object entity, HashSet<object> visited, string prefix) { var propertyReports = new List<DataPropertyReport>(); // Exit early if entity is null or already processed (avoids circular references) if (entity == null || visited.Contains(entity)) { return propertyReports; } visited.Add(entity); var properties = entity.GetType().GetProperties(); foreach (var property in properties) { var value = property.GetValue(entity, null); // Build full dot-separated property path (e.g., "Article.SubCategory.Name") var fullPropertyName = string.IsNullOrEmpty(prefix) ? property.Name : $"{prefix}.{property.Name}"; // Check if the property is a simple type (primitive, string, enum, or nullable variant) var propertyType = property.PropertyType; var underlyingType = Nullable.GetUnderlyingType(propertyType); var isSimpleType = underlyingType != null ? underlyingType.IsPrimitive || underlyingType == typeof(string) || underlyingType.IsEnum : propertyType.IsPrimitive || propertyType == typeof(string) || propertyType.IsEnum; if (isSimpleType) { // Add simple type property to the result list propertyReports.Add(new DataPropertyReport( fullPropertyName, value != null ? value.ToString() : string.Empty, 1)); } else { // Recursively process nested complex objects var nestedReports = GetPrimitiveProperties(value, visited, fullPropertyName); propertyReports.AddRange(nestedReports); } } return propertyReports; }
Key Changes Explained
- Recursive Traversal: The private helper method digs into complex types (like
Article,Category,Model) and extracts their properties instead of treating them as single values. - Circular Reference Protection: The
HashSet<object>tracks already processed objects to prevent infinite loops in self-referential structures (e.g., aCategorywhoseCategoryFatherpoints back to itself). - Clear Property Paths: The
prefixparameter builds a dot-separated path for nested properties, so you can easily identify where each value originates (e.g.,Article.Model.Nameinstead of justName). - Simple Type Detection: We explicitly distinguish between simple types (primitives, strings, enums, nullables) and complex types, ensuring only leaf-level values are added to the report.
Example Output
For a populated Unity instance, your resulting DataPropertyReport list will include entries like:
Text: "Sample unity text"NumberOfPages: "10"Article.Name: "Introduction to Unity"Article.SubCategory.Name: "Game Development"Article.Model.Name: "Unity Engine"
Notes
- If you need to handle collections (e.g.,
List<Category>), you can extend the logic to iterate over collection items and append indices to the property path (e.g.,Categories[0].Name). - The
ToString()override inArticlewon’t be used here—we’re extracting its individual properties instead of relying on its string representation.
内容的提问来源于stack exchange,提问作者Daniel Acevedo
相关产品推荐
相关产品推荐

