从抽象类调用GetMethod来获取子类的方法?(Call GetMethod from abstract class to get method of child class?)

编程入门 行业动态 更新时间:2024-10-12 03:22:45
从抽象类调用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

更多推荐

本文发布于:2023-08-08 01:00:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1466648.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:子类   方法   抽象类   GetMethod   Call

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!