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

如何在C#中利用反射通过父类获取嵌套属性的完整名称?

How to Get Full Nested Property Names via Reflection in C#

Great question! When dealing with nested class hierarchies like your Student → Grade → GradGroup setup, you can use reflection paired with recursion to traverse every property and build their fully qualified names. Let’s walk through a practical, reusable solution.

Core Idea

The approach is straightforward:

  • For "leaf" properties (value types, strings, or nullable value types), we just capture their name (plus any parent prefix we’ve built up).
  • For properties that are custom class types (like Grade on Student), we recursively dig into their properties, prepending the parent property name to construct the full path.

Reusable Code Implementation

Here’s a helper class with a method that handles all the heavy lifting:

using System;
using System.Collections.Generic;
using System.Reflection;

public static class ReflectionPropertyHelper
{
    public static List<string> GetFullNestedPropertyNames(Type rootType, string parentPrefix = "")
    {
        var fullPropertyNames = new List<string>();
        
        // Grab all public instance properties of the current type
        foreach (var property in rootType.GetProperties(BindingFlags.Public | BindingFlags.Instance))
        {
            // Resolve nullable types to their underlying value type
            var propertyType = Nullable.GetUnderlyingType(property.PropertyType) ?? property.PropertyType;
            
            // Build the full name for the current property
            var currentFullName = string.IsNullOrEmpty(parentPrefix)
                ? property.Name
                : $"{parentPrefix}.{property.Name}";
            
            // Check if this is a leaf property (no nested classes to traverse)
            if (propertyType.IsValueType || propertyType == typeof(string))
            {
                fullPropertyNames.Add(currentFullName);
            }
            else
            {
                // Recursively get nested properties and add them to our list
                var nestedNames = GetFullNestedPropertyNames(propertyType, currentFullName);
                fullPropertyNames.AddRange(nestedNames);
            }
        }

        return fullPropertyNames;
    }
}

How to Use This

Call the method with your root class type (like Student) to get all fully qualified nested property names:

// Retrieve all nested property names for the Student class
var studentPropertyPaths = ReflectionPropertyHelper.GetFullNestedPropertyNames(typeof(Student));

// Print the results to verify
foreach (var path in studentPropertyPaths)
{
    Console.WriteLine(path);
}

Expected Output

For your class structure, the output will look like this:

StudentID
StudentName
DateOfBirth
Grade.GradeId
Grade.GradeName
Grade.Section
Grade.GradGroup.[YourGradGroupProperty1]
Grade.GradGroup.[YourGradGroupProperty2]
// ... and so on for all properties in GradGroup

Key Details to Note

  • Nullable Support: The code uses Nullable.GetUnderlyingType to handle nullable value types (like DateTime? DateOfBirth) correctly, treating them as leaf properties instead of trying to traverse them.
  • Binding Flags: We target public instance properties by default—adjust the BindingFlags if you need to include non-public or static properties.
  • Leaf Property Logic: We skip recursion for value types and strings because these are typically end points. If you have other built-in types you want to treat as leaves, just add them to the condition.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 06:34:01