使用方法字符串名称从其基抽象类调用派生类方法



我正在尝试一种动态方法来调用方法派生类。 我有2节课 第一个类是一个基类,它有一个方法,允许我按名称调用方法。

public abstract class Main(){
public void DoCall (string methodName){
Type thisType = this.GetType();
MethodInfo theMethod = thisType.GetMethod(methodName);
theMethod.Invoke(this, null);
}
}

第二个是一个派生类,它有一个我想调用的方法

public abstract class DoSomething(){
public void Print(){
Console.info("HELLO WORLD")
}
}

最后,我想使用 DoCall(( 方法调用 Print((,因为我会收到一个类型为 DoSomething(( 的对象,但我只能将其转换为 Main((;

public void ActOnIt(object Obj){
Main received = (Main)Obj; 
received.DoCall("Print");
} 

我想说这是可能的,但也许我没有正确的方法。目前,我没有例外,但我也没有看到控制台打印。

你做事的方式可能不是正确的设计。不过,它应该在技术上起作用。

class Program
{
static void Main(string[] args)
{
ActOnIt(new DoSomething());
Console.ReadKey();
}
public static void ActOnIt(object Obj)
{
Main received = (Main)Obj;
received.DoCall("Print");
}
}
public class DoSomething:Main
{
public void Print()
{
Console.WriteLine("HELLO WORLD");
}
}
public abstract class Main
{
public void DoCall(string methodName)
{
Type thisType = this.GetType();
MethodInfo theMethod = thisType.GetMethod(methodName);
theMethod.Invoke(this, null);
}
}