3 回答
TA貢獻1818條經驗 獲得超7個贊
如果無法訪問 Player 類,一種選擇是僅在設定的時間間隔內檢查所有玩家的 Life 變量的值。
您需要在 Game 類中保留局部變量,以跟蹤 Life 變量之前設置的內容,但是每當您注意到 Life 變量的值之一發生更改時,您都可以在 Game 中執行您需要的任何代碼類,這將為您提供與事件處理程序基本相同的行為(盡管可能不那么有效)。
class Game {
List<Player> playerList;
ArrayList lifeValues;
System.Timers.Timer lifeCheckTimer;
Game() {
playerList = new List<Player>();
//add all players that have been instantiated to the above list here
lifeValues = new ArrayList();
//add all the player.Life values to the above list here
//these will need to be added in the same order
lifeCheckTimer = new System.Timers.Timer();
lifeCheckTimer.Elapsed += new ElapsedEventHandler(lifeCheckElapsed);
//you can change the 500 (0.5 seconds) below to whatever interval you want to
//check for a change in players life values (in milliseconds)
lifeCheckTimer.Interval = 500;
lifeCheckTimer.Enabled = true;
}
private static void lifeCheckElapsed(object source, ElapsedEventArgs e)
{
for (int i = 0; i < playerList.Count(); i ++) {
if (((Player)playerList[i]).Life != lifeValues[i])
OnPlayerLifeChange();
lifeValues[i] = ((Player)playerList[i]).Life;
}
}
}
TA貢獻1827條經驗 獲得超8個贊
一種常見的方法是在 Player 類中實現 INotifyPropertyChanged 接口,將 Life 從字段更改為屬性,并從 setter 引發 PropertyChanged 事件。
class Player : INotofyPropertyChanged
{
private int _life;
public int Life
{
get { return _life; }
set { _life = value; OnPropertyChanged("Life"); }
}
....
}
然后游戲可以訂閱所有玩家的 PropertyChanged 事件并做出相應的反應。
TA貢獻1993條經驗 獲得超6個贊
編寫 Player 類的人需要添加一個公共方法來檢查變量的任何更新Life。那么你只需要使用該方法即可。
如果這個人沒有編寫這樣的方法,那么你就無法訪問它(這就是為什么封裝很重要,否則任何人都可以訪問不應該訪問的東西)
- 3 回答
- 0 關注
- 220 瀏覽
添加回答
舉報
