如何获取属性值?需提取实体原始属性及关联对象指定属性
Solution: Extract Primitive Properties + Text from Complex Types
Got it, let's adjust your existing method to meet your requirement—capturing primitive properties directly, and pulling the Text value from complex types like Header and Footer. Here's the modified code with clear explanations:
Modified Code
public static List<DataPropertyReport> GetDocumentProperties<T>(T entity) { var properties = entity.GetType().GetProperties(); List<DataPropertyReport> info = new List<DataPropertyReport>(); foreach (var property in properties) { object value = property.GetValue(entity, null); if (value == null) continue; // Skip null values to avoid null reference exceptions Type propertyType = value.GetType(); // Handle primitive types, string, and DateTime if (propertyType.IsPrimitive || propertyType == typeof(string) || propertyType == typeof(DateTime)) { info.Add(new DataPropertyReport(property.Name, value.ToString(), 1)); } else { // Check if the complex type has a public, readable "Text" property of type string var textProperty = propertyType.GetProperty("Text", typeof(string)); if (textProperty != null && textProperty.CanRead) { var textValue = textProperty.GetValue(value, null)?.ToString() ?? string.Empty; // Use a formatted name like "Header.Text" to clarify the source info.Add(new DataPropertyReport($"{property.Name}.Text", textValue, 1)); } // Optional: Add else clause here if you need to handle other complex types differently } } return info; }
Key Changes Explained
- Null Safety: Added a check to skip null property values, preventing null reference errors when accessing type information or property values.
- Complex Type Handling: For non-primitive properties, we use reflection to look for a public, readable
Textproperty of typestring. If found, we extract its value. - Clear Naming: The property name in the report is formatted as
{ComplexPropertyName}.Text(e.g.,Header.Text) so you can easily identify where the value originates. - Flexibility: The code is easy to extend—if you need to handle other complex properties later, you can add additional checks in the
elseblock.
Example Usage
Let's test this with a sample Document instance:
var sampleDoc = new Document { Text = "Core document content", Description = "Annual report draft", NumberOfPages = 12, Header = new Header { Id = 42, Text = "2024 Annual Report" }, Footer = new Footer { Id = 99, Text = "Confidential" } }; var propertyReports = GetDocumentProperties(sampleDoc);
The resulting propertyReports list will contain these entries:
Text: "Core document content"Description: "Annual report draft"NumberOfPages: "12"Header.Text: "2024 Annual Report"Footer.Text: "Confidential"
内容的提问来源于stack exchange,提问作者Daniel Acevedo
相关产品推荐
相关产品推荐

