C#GetMethod不返回父方法

Seb*_*ste 12 c# methods inheritance static getmethod

我有以下类树:

public class A
{
    public static object GetMe(SomeOtherClass something)
    {
        return something.Foo();
    }
}

public class B:A
{
    public static new object GetMe(SomeOtherClass something)
    {
        return something.Bar();
    }
}

public class C:B
{

}

public class SomeOtherClass
{

}
Run Code Online (Sandbox Code Playgroud)

鉴于SomeOtherClass parameter = new SomeOtherClass())这工作:

typeof(B).GetMethod("GetMe", new Type[] { typeof(SomeOtherClass) })).Invoke(null, parameter));
Run Code Online (Sandbox Code Playgroud)

但是这个:

typeof(C).GetMethod("GetMe", new Type[] { typeof(SomeOtherClass) })).Invoke(null, parameter));
Run Code Online (Sandbox Code Playgroud)

抛出一个NullReferenceException,虽然我希望它会调用与上面完全相同的方法.

我试过几个绑定标志无济于事.有帮助吗?

Jon*_*eet 20

您应该使用一个带参数的重载BindingFlags,并包括FlattenHierarchy.

指定应返回层次结构中的公共和受保护静态成员.不返回继承类中的私有静态成员.静态成员包括字段,方法,事件和属性.不返回嵌套类型.

(编辑删除关于私有静态方法的观点,现在问题已被更改为公开.)


das*_*ght 5

您需要将BindingFlags.FlattenHierarchy标志传递GetMethod给搜索层次结构:

typeof(C).GetMethod("GetMe", BindingFlags.FlattenHierarchy, null, new Type[] { typeof(SomeOtherClass) }, null)).Invoke(null, parameter));
Run Code Online (Sandbox Code Playgroud)