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,虽然我希望它会调用与上面完全相同的方法.
我试过几个绑定标志无济于事.有帮助吗?
您需要将BindingFlags.FlattenHierarchy标志传递GetMethod给搜索层次结构:
typeof(C).GetMethod("GetMe", BindingFlags.FlattenHierarchy, null, new Type[] { typeof(SomeOtherClass) }, null)).Invoke(null, parameter));
Run Code Online (Sandbox Code Playgroud)