从抽象类调用GetMethod来获取子类的方法?

时间:2014-01-30 14:35:01

标签: c# reflection

我有类似的东西

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()它可以正常工作。我并不感到惊讶,因为它没有正确连接,但有没有办法可以使它工作?

1 个答案:

答案 0 :(得分:5)

您需要添加公开|静态修饰符:

var methodInfo = thisType.GetMethod("DoSomething", 
         System.Reflection.BindingFlags.FlattenHierarchy 
         | System.Reflection.BindingFlags.Public
         | System.Reflection.BindingFlags.Static);

然后它会在当前类或它的继承者中搜索公共静态方法