我有一個父類以及所有從父類中獲取inhirits的子類(Child1,Child2,Child3)。我試圖將這些子對象強制轉換爲父類,但是我得到了無效的強制類型轉換例外。將子對象作爲列表<object>存儲爲父對象
Child1 aChild1 = new Child1();
Child2 aChild2 = new child2();
List<object> childsList = new List<object>();
childsList.Add(aChild1);
childsList.Add(aChild2);
foreach(object child in childsList)
{
Parent p = (Parent)child;//Here I got the exception
}
我可以使用'is'來檢查子對象的類型。
if (child is Child1){}
else if (child is Child2{} .....
或通過讓孩子的類型,並將其與類名知道類型:
if (child.GetType().Name.Equals("Child1")
//Do whatever
else if (child.GetType().Name.Equals("Child2")
//Do another whatever :D
但我在尋找一個更好的方法來投孩子的他們的父類。的List<object>
沒有辦法,如果對象真正從'Parent'獲得投將拋出。檢查你的假設。 – Jon
顯示你的Child1和Parent的實現,我猜是parent是Child1的一個屬性。父p =((Child1)孩子).Parent? – Peter