从抽象类调用GetMethod来获取子类的方法?(Call GetMethod from abstract class to get method of child class?)
我有类似的东西
public abstract class Parent { public void BeginRequest() { var thisType = this.GetType(); var methodInfo = thisType.GetMethod("DoSomething", System.Reflection.BindingFlags.FlattenHierarchy); Response.Write(methodInfo.Invoke(this, null)); } } public class Child : Parent { public static string DoSomething() {....} }问题是methodInfo总是设置为null。 如果我在Parent中创建DoSomething()它可以正常工作。 我并不感到惊讶它没有正确接线,但有没有办法可以使它工作?
I have something similar to this
public abstract class Parent { public void BeginRequest() { var thisType = this.GetType(); var methodInfo = thisType.GetMethod("DoSomething", System.Reflection.BindingFlags.FlattenHierarchy); Response.Write(methodInfo.Invoke(this, null)); } } public class Child : Parent { public static string DoSomething() {....} }Problem is that methodInfo is always setting to null. If I create DoSomething() inside Parent it works fine. I'm not really surprised that it doesn't wire up properly, but is there a way that I can make it work?
最满意答案
你需要添加Public | 静态修饰符:
var methodInfo = thisType.GetMethod("DoSomething", System.Reflection.BindingFlags.FlattenHierarchy | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static);然后它将在当前类或它的继承者中搜索公共静态方法
You need to add Public | Static modifiers:
var methodInfo = thisType.GetMethod("DoSomething", System.Reflection.BindingFlags.FlattenHierarchy | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static);Then it will search for public static method in current class or it's inheritors
更多推荐
发布评论