我有一个抽象类(Parent),其函数名为funcA.Parent有4个childern,用户需要选择访问哪个.我需要做的是访问用户选择的子子类中的覆盖方法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();
}
Run Code Online (Sandbox Code Playgroud)
儿童:
public class ChildA: Parent
{
public string PropE {get; set;}
public string PropF {get; set;}
public override void FuncA()
{
// Some Code
}
}
Run Code Online (Sandbox Code Playgroud)
主要:
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.
}
Run Code Online (Sandbox Code Playgroud)
字符串类型被验证为现有子项.用户无法输入不存在的类型.
如果您总是调用抽象方法,则只需将对象转换为a Parent并以类型安全的方式调用该方法:
Type t = Type.GetType("ChildA");
Parent p = Activator.CreateInstance(t) as Parent;
p.FuncA();
Run Code Online (Sandbox Code Playgroud)
由于FuncA是虚拟的,因此将使用派生最多的实现.
| 归档时间: |
|
| 查看次数: |
152 次 |
| 最近记录: |