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

如何无需遍历动态获取嵌套类中指定名称的常量值?

无需遍历嵌套类的高效解决方案

当然有更优的处理方式!你完全不用逐个遍历所有嵌套类,直接利用Type.GetNestedType()方法就能精准定位到目标嵌套类型,一步到位获取对应的常量值,代码更简洁,性能也更出色。

优化后的代码实现

public class SecondClass { 
    public class SecondClassOne { 
        public const string A = "AValue 1"; 
        public const string B = "BValue 1"; 
        public const string C = "CValue 1"; 
    } 
    public class SecondClassTwo { 
        public const string A = "AValue 2"; 
        public const string B = "BValue 2"; 
        public const string C = "CValue 2"; 
    } 
}

var className = "SecondClassTwo";
var name = "A";

// 直接按名称获取目标嵌套类型
Type targetNestedType = typeof(SecondClass).GetNestedType(className);

if (targetNestedType != null)
{
    // 获取指定的常量字段
    FieldInfo constantField = targetNestedType.GetField(name);
    
    // 额外校验:确保这是const常量(const字段会标记为IsLiteral且IsInitOnly为false)
    if (constantField != null && constantField.IsLiteral && !constantField.IsInitOnly)
    {
        Console.WriteLine(constantField.GetValue(null)); // 输出:AValue 2
    }
}

补充细节说明

  • 适配不同访问权限:如果你的嵌套类不是public(比如internal或private),可以给GetNestedType传入绑定标志参数来匹配,示例如下:
    Type targetNestedType = typeof(SecondClass).GetNestedType(
        className, 
        BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static
    );
    
  • 提升可靠性:添加IsLiteral和!IsInitOnly的校验,是为了区分const常量和readonly字段(readonly字段的IsInitOnly为true),避免误获取非常量值。

这种方式省去了遍历所有嵌套类型的开销,尤其是当嵌套类数量越来越多时,性能优势会更显著,代码也更易维护。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 09:30:29