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

C# 11静态继承反射调用异常:未重写静态属性子类报错

解决C# 11静态继承下反射调用未重写静态成员的问题

问题原因

直接写Subclass2.MyProp时,编译器会做语法糖处理:因为子类没定义自己的静态MyProp,自动把调用指向基类MyBaseClass.MyProp。但反射的InvokeMember默认不会自动向上遍历继承链找静态成员——除非你明确指定对应的绑定标志,否则它只会在Subclass2自身的成员里找,找不到就抛MethodNotFoundException。

解决方案一:修正BindingFlags参数

给InvokeMember补充完整的绑定标志,加上BindingFlags.Public | BindingFlags.Static | BindingFlags.FlattenHierarchy,让反射遍历继承链查找公共静态属性:

// 正常输出 "default",和直接访问Subclass2.MyProp结果一致
var test6 = typeof(Subclass2).InvokeMember("MyProp",
    BindingFlags.GetProperty | BindingFlags.Public | BindingFlags.Static | BindingFlags.FlattenHierarchy,
    null, null, null);

解决方案二:手动遍历继承链(灵活场景)

如果需要处理非公共成员、自定义查找逻辑等复杂情况,可以手动遍历类型的继承链,逐个检查是否存在目标静态属性:

public static object? GetInheritedStaticProperty(Type type, string propertyName)
{
    Type? currentType = type;
    while (currentType != null)
    {
        PropertyInfo? prop = currentType.GetProperty(propertyName, BindingFlags.Public | BindingFlags.Static);
        if (prop != null)
        {
            return prop.GetValue(null);
        }
        currentType = currentType.BaseType;
    }
    throw new MissingMemberException($"未找到静态属性 {propertyName}");
}

调用示例:

var test6 = GetInheritedStaticProperty(typeof(Subclass2), "MyProp"); // 输出 "default"

补充说明

原代码中InvokeMember只传了BindingFlags.GetProperty,这个标志必须配合访问权限、成员类型等标志一起使用,否则反射无法正确定位成员。FlattenHierarchy标志的作用就是让反射把基类的公共静态成员纳入当前类型的查找范围,从而匹配到基类的MyProp。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 10:22:54