我有一个抽象类(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/