【问题标题】:Call derived class method from it's base abstract class using the methods string name使用方法字符串名称从其基抽象类调用派生类方法
【发布时间】:2018-09-20 22:05:58
【问题描述】:

我正在尝试一种能够调用方法派生类的动态方法。 我有 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")
     }
}

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

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

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

【问题讨论】:

  • 尽管“基于反射”的调用很花哨,但它们对您的执行成本有巨大的影响。根据我自己的经验,每次我“需要”在 C# 中使用反射时,我最终还是最好实现某种形式的“代理”类。
  • 然而,在研究这个解决方案时,您仍然需要一个接口来允许所有派生类都有一个标准。问题是当我收到这些派生类时,每一个都是独一无二的,并且有自己的功能。我想允许客户端按名称访问这些功能。

标签: c# inheritance abstract-class invoke


【解决方案1】:

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

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);
    }
}

【讨论】:

  • 感谢您的回答。什么点使这个设计不好?我可以看到使用反射很昂贵,调用派生类方法很麻烦。但是,ActOnIt() 必须足够通用才能加载任何 Main() 派生类,并允许调用其方法。您还有其他建议吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-03-28
  • 1970-01-01
  • 1970-01-01
  • 2021-09-10
  • 2017-05-05
  • 2014-03-17
相关资源
最近更新 更多