C#GetMethod不返回父类的方法(C# GetMethod doesn't retur

2019-06-28 03:36发布

我有以下分类:

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
{

}

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

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

但是这个:

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

抛出一个NullReferenceException ,而我希望它会调用完全相同的方法比上面。

我试过几个绑定标志无济于事。 任何帮助吗?

Answer 1:

您应该使用一个重载采取BindingFlags参数,包括FlattenHierarchy

指定公共和保护的静态成员最多的层次应返回。 在继承类私有静态成员没有回来。 静态成员包括字段,方法,事件和属性。 嵌套类型不返回。

(编辑删除有关私人静态方法的地步,现在的问题已经改变,使他们公开。)



Answer 2:

你需要传递BindingFlags.FlattenHierarchy标志GetMethod为了寻找了层次:

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


文章来源: C# GetMethod doesn't return a parent method