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

如何通过层级路径获取PropertyInfo?GetProperty不支持该路径格式

通过层级路径获取PropertyInfo的实现方案

当然有办法实现这种嵌套属性的PropertyInfo获取!既然内置的GetProperty方法不支持层级路径,我们可以自己封装一个工具方法,通过逐层解析路径节点的方式来实现。

核心思路

把层级路径(比如"window.position.x")按.分割成单个属性名,然后从初始类型(这里是WindowManager的类型)开始,依次获取每个层级的PropertyInfo,并将当前类型更新为该属性的PropertyType,直到遍历完所有路径节点,最终得到目标属性的PropertyInfo。

代码实现示例(C#)

using System;
using System.Reflection;

public static class PropertyInfoHelper
{
    public static PropertyInfo GetPropertyByPath(Type targetType, string propertyPath, BindingFlags bindingFlags = BindingFlags.Public | BindingFlags.Instance)
    {
        if (targetType == null)
            throw new ArgumentNullException(nameof(targetType));
        if (string.IsNullOrWhiteSpace(propertyPath))
            throw new ArgumentException("Property path cannot be null or empty.", nameof(propertyPath));

        string[] propertyNames = propertyPath.Split('.');
        Type currentType = targetType;
        PropertyInfo targetProperty = null;

        foreach (string propName in propertyNames)
        {
            targetProperty = currentType.GetProperty(propName, bindingFlags);
            if (targetProperty == null)
            {
                throw new InvalidOperationException($"Property '{propName}' not found on type '{currentType.FullName}'");
            }
            currentType = targetProperty.PropertyType;
        }

        return targetProperty;
    }
}

使用方式

比如要获取WindowManager里window.position.x的PropertyInfo,可以这样调用:

Type managerType = typeof(WindowManager);
PropertyInfo xProperty = PropertyInfoHelper.GetPropertyByPath(managerType, "window.position.x");

扩展说明

  • 如果需要访问私有/保护属性,可以调整bindingFlags参数,比如传入BindingFlags.NonPublic | BindingFlags.Instance。
  • 可以根据需求调整异常逻辑,比如返回null而非抛出异常,或者添加日志记录。
  • 如果路径包含索引器(比如window.items[0].name),还可以进一步扩展方法来解析索引部分,适配更复杂的场景。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 07:19:06