2014-03-12 31 views
3

我有一個父類以及所有從父類中獲取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>

+3

沒有辦法,如果對象真正從'Parent'獲得投將拋出。檢查你的假設。 – Jon

+0

顯示你的Child1和Parent的實現,我猜是parent是Child1的一個屬性。父p =((Child1)孩子).Parent? – Peter

回答

1

使用List<Parent>相反,你可以使用LINQ

IEnumerable<Parent> result = childsList.Cast<Parent>().ToList(); 
+0

這個問題是我使用相同的列表來存儲父對象的子對象。 – Mhdali

+0

如果某些元素不繼承父類,則應檢查其類型if(child is Parent){} else {} –

+0

@Mhdali:那麼當您將這些對象轉換爲'Parent'時,您會發生什麼? – Jon

1

投它,我需要檢查這些 孩子的某些屬性從父類inhirited對象

如果屬性被繼承沒有必要施放,應該已經在兒童層面上可見。

順便說一下,如果您投射並得到一個異常,這意味着該類型不會繼承 基類。

1

當你列舉你的列表您可以使用動態類型:

foreach(dynamic child in childsList) 
{ 
    child.ParentPropertyName; // here you can check Parent property value 
} 
4

鑑於您的評論「問題是我使用相同的列表來存儲不是父母的孩子的對象。」,此列表包含Parent對象和其他無關的對象的組合。

然後,你必須以優雅的方式過濾掉它們。最簡單的是可能與LINQ的OfType方法:

List<Parent> result = childsList.OfType<Parent>().ToList(); 

這不是Parent將被忽略任何對象。

這就是說,這是(通常)一個顯著代碼味道和更理想的情況是,你不混合存儲在上市的對象,所以childsList可以在第一時間將強類型的List<Parent> ,但很難在不知道應用程序設計的其餘部分的情況下針對「更好的方法」的具體內容發表評論。

編輯:這是它與現有的代碼使用:

foreach(Parent p in childsList.OfType<Parent>()) 
{ 

} 
相關問題