c# - 获取未知类型的方法并运行它 c#

标签 c# inheritance

我有一个抽象类(Parent),它有一个名为 funcA 的函数。 parent 有 4 个 child ,用户需要选择访问哪一个。 我需要做的是访问用户选择的子类中的重写方法 funcA 并激活它。

家长:

public abstract class Parent
{
 public string PropA {get; set;}
 public string PropB {get; set;}
 public DateTime PropC {get; set;}
 public DateTime PropD {get; set;}

 public abstract void FuncA();

}

child :

public class ChildA: Parent
{
   public string PropE {get; set;}
   public string PropF {get; set;}

   public override void FuncA()
   {
     // Some Code
   }
}

主要内容:

public static void Main(string[] args)
{
  Console.WriteLine("Enter the type of child: ");
  string type = Console.Readline();

  // I need to identify which child is type, access that child's FuncA and
  // run it.
}

字符串类型被验证为现有子类型。用户无法输入不存在的类型。

最佳答案

如果您总是调用抽象方法,您只需将对象转换为Parent 并以类型安全的方式调用该方法:

Type t = Type.GetType("ChildA");
Parent p = Activator.CreateInstance(t) as Parent;
p.FuncA();

由于 FuncA 是虚拟的,因此将使用最派生的实现。

关于c# - 获取未知类型的方法并运行它 c#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37420671/

相关文章:

c# - MongoDb 传递谓词参数

c# - 将时间戳添加到 Trace.WriteLine()

c# - WPF 使用相对路径从程序集中的任何位置访问资源

java - 为什么子类运行父类(super class)构造函数?

java - 多级继承: Calling a method only ONE level higher from subclass

c# - Wpf 网页浏览器 + ftp 服务器

c# - 如何让 AutoMapper 处理自定义命名约定?

java - 如何创建继承泛型类的对象

node.js - Mongoose 模式继承和模型填充

c++ - 基派生类关系