[英]How do i dynamically cast a child class from its parent class?
这是我想要做的。 我在ParentForm中有一个类,它的本质是一个Form类,其中添加了2件事。
然后我做的其他表格我都继承了ParentForm ,所以我喜欢
class f1: ParentForm
class f2: ParentForm
class f3: ParentForm
etc...
现在让我们说我在f1和f2中都有一个按钮,都可以打开f3表单,而f3表单构造函数如下所示:
public f3(ParentForm parent)
我使用它来将变量传递回原始形式(在本例中为f1或f2 ),以将数据添加到那里的List或其他任何形式。
现在出现了我的问题,我现在一直在做这样的事情:
if (parent.GetType() == typeof(f1))
{
((f1)parent).list.Add("a");
}
else if (parent.GetType() == typeof(f2))
{
((f2)parent).list.Add("a");
}
因此,我为每位父母创建了一张支票,我该如何动态地这样做呢? 就像是
((parent.GetType())parent).list.Add("a");
但是,这当然行不通,有人解决了吗?
有两种选择:
ParentForm
包含列表的定义:
public List<string> TheList { get;private set;}
每种形式都通过abstract
实现实现相同的interface
:
public abstract class ParentForm : IFormWithList { public abstract List<string> TheList { get; } }
其中IFormWithList
是:
List<string> TheList { get; }
然后,您应该在每个派生类中声明它:
public class f1 : ParentForm { public override List<string> TheList { get { return this.list; } } }
根据您的评论,您可以定义以下Interface
:
IMyForm
{
}
IFormWithList:IMyForm
{
ListBox ListBox { get; set; }
}
IFormWithTreeView:IMyForm
{
TreeView TreeView { get; set; }
}
您的表单继承自适当的Interface
:
class f1: IWithListForm
class f2: IWithListForm
class f3: IWithListForm
现在,您可以注入IMyForm
而不是ParentForm
:
public f3(IMyForm parent)
我不确定这是最好的解决方案,但是在这里我将如何做:
abstract class ParentForm{
...
public abstract void Update<T>(T updateValue)
}
public class f1 : ParentForm{
...
private List<string> list;
public override void Update(string value){
list.Add(value);
}
}
public class f2 : ParentForm{
....
private List<int> list;
public override void Update(int val){
...
}
}
等等
实际上,您也可以使用virual
方法或属性来实现相同的目标。 如果声明了Add方法或Property虚拟,则将自动调用它们各自的方法或属性。 意思是如果你有:
class Parent
{
public virtual void Add(string msg)
{
System.Windows.Forms.MessageBox.Show("Parent got msg");
}
}
class child1:Parent
{
public override void Add(string msg)
{
System.Windows.Forms.MessageBox.Show("Child 1 Got Msg");
}
}
class child2 : Parent
{
public override void Add(string msg)
{
System.Windows.Forms.MessageBox.Show("Child 2 Got Msg");
}
}
像这样简单地使用它们:
Parent p;
...
p = new child1();
p.Add("Test"); // will call child1's add method
p = new child2();
p.Add("Test"); // will call child2's add method
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.