[英]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.