PlayerBase是FieldPlayer和GoalKeeper的基類。我在FieldPlayer和GoalKeeper中有stateMachine memeber。但是在MyList中,FieldPlayer和GoalKeeper都被視爲PlayerBase。我如何確保獲得正確類型的stateMachine?我應該不知何故檢查類型,然後typecast?根據對象類型訪問正確的成員
foreach (PlayerBase p in MyList)
{
// Here I need to access p.stateMachine for FieldPlayer or GoalKeeper, depends what p is.
}
感謝
is stateMachine不是PlayerBase的成員? – TheCodeKing
使用多態時檢查實際的類型是一種代碼異味。你爲什麼要區分? – BrokenGlass
nope,不能這樣做,它是我爲FieldPlayer和GoalKeepeer – pokoko222