C#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 { }
鉴于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
,我希望它会调用与上面完全相同的方法。
我试过几个绑定标志无济于事。 有帮助吗?
您应该使用一个带有BindingFlags
参数的重载 ,并包含FlattenHierarchy
。
指定应返回层次结构中的公共和受保护静态成员。 不返回inheritance类中的私有静态成员。 静态成员包括字段,方法,事件和属性。 不返回嵌套类型。
(编辑删除关于私有静态方法的观点,现在问题已被更改为公开。)
您需要将BindingFlags.FlattenHierarchy
标志传递给GetMethod
才能搜索层次结构:
typeof(C).GetMethod("GetMe", BindingFlags.FlattenHierarchy, null, new Type[] { typeof(SomeOtherClass) }, null)).Invoke(null, parameter));