C# 获取未知类型';s方法并运行它#

C# 获取未知类型';s方法并运行它#,c#,inheritance,C#,Inheritance,我有一个抽象类(父类)和一个名为funcA的函数。 父项有4个子项,用户需要选择要访问的子项。 我需要做的是访问用户选择的子类中的重写方法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;}

我有一个抽象类(父类)和一个名为funcA的函数。 父项有4个子项,用户需要选择要访问的子项。 我需要做的是访问用户选择的子类中的重写方法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();

}
儿童:

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

   public override void FuncA()
   {
     // Some Code
   }
}
主要内容:

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

如果总是调用抽象方法,则可以将对象强制转换为父对象,并以类型安全的方式调用该方法:

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

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

使用反射<代码>类型t=Type.GetType(该类型);t、 GetMethod(“FuncA”).Invoke(…)我尝试过,但Invoke需要一个对象来对其执行该方法。我所拥有的只是类型,无法创建未知类型的对象。@EinatLugassy您不能或不知道如何创建?@DStanley我尝试过,但总有一种方法我不知道,我无法找到使用“new”键或使用GetType()创建新对象的方法。展示您所做的尝试,以便确定真正的问题。
Type t = Type.GetType("ChildA");
Parent p = Activator.CreateInstance(t) as Parent;
p.FuncA();