2017-02-16 130 views
0
public class Activity 
{ 
    public games _Games {get;set;} 
    public sports _Sports {get;set;} 
} 

public class games : PropertyChangedBase 
{ 
    public int player 
    { 
     get; 
     set; //have if- else statement 
    } 
} 

public class sports : PropertyChangedBase 
{ 
    public int sub{get;set;} 
} 

目的:當遊戲玩家超過2個,我想更新運動的副變量,以10訪問父級對象

問:如何訪問父類和更新運動類變量?

+2

這是一個相當平凡的問題,可能以多種不同的方式解決。請你可以告訴我們你已經嘗試了什麼,以及爲什麼它不起作用的代碼。 – Ben

+0

歡迎來到StackOverflow。如果有任何答案對你有幫助,你可以看看[如何做 - 接受答案 - 工作](http://meta.stackexchange.com/questions/5234/how-does-accepting -an-answer-work)帖子 –

回答

0

您可以使用一個事件來告知Activity類需要更新的事件。

public class games 
{ 
    public event UpdatePlayerSubDelegate UpdatePlayerSub; 

    public delegate void UpdatePlayerSubDelegate(); 
    private int _player; 

    public int player 
    { 
     get { return _player; } 
     set 
     { 
      _player = value; 
      if (_player > 2) 
      { 
       // Fire the Event that it is time to update 
       UpdatePlayerSub(); 
      }     
     } 
    }   
} 

在Activity類中,您可以在構造函數中註冊事件並向事件處理函數中寫入必要的更新。你的情況分至10:

public class Activity 
{ 
    public games _Games { get; set; } 
    public sports _Sports { get; set; } 

    public Activity() 
    { 
     this._Games = new games(); 
     this._Games.UpdatePlayerSub += _Games_UpdatePlayerSub; 
     this._Sports = new sports(); 
    } 

    private void _Games_UpdatePlayerSub() 
    { 
     if (_Sports != null) 
     { 
      _Sports.sub = 10; 
     } 
    } 
} 

編輯 我剛纔看到的標籤INotifyPropertyChanged。當然你也可以使用這個界面和提供的事件。實現接口,如下:

public class games : INotifyPropertyChanged 
{ 
    public event PropertyChangedEventHandler PropertyChanged; 

    private int _player; 
    public int player 
    { 
     get { return _player; } 
     set 
     { 
      _player = value; 
      if (_player > 2) 
      { 
       // Fire the Event that it is time to update 
       PropertyChanged(this, new PropertyChangedEventArgs("player")); 
      }     
     } 
    }   
} 

而在Activity類寄存器再次在構造函數中的事件:

public Activity() 
{ 
    this._Games = new games(); 
    this._Games.PropertyChanged += _Games_PropertyChanged; 
    this._Sports = new sports(); 
} 

,並宣佈事件處理程序的身體:

private void _Games_PropertyChanged(object sender, PropertyChangedEventArgs e) 
{ 
    if (_Sports != null) 
    { 
     _Sports.sub = 10; 
    } 
} 

_Sports.sub將自動更新。希望能幫助到你。當然還有其他方法可以完成此更新。這只是第一個想到的問題

0

您需要創建一個Activity的實例。您還需要在它

Activity activity = new Activity(); 
activity._Sports = new sports(); 
activity._Sports.sub = 10; 

或使用對象tantalizer

Activity activity = new Activity 
{ 
    _Sports = new sports() 
}; 

activity._Sports.sub = 10; 

順便說初始化_SportsActivity不是父類的sportsActivity擁有sports對象作爲成員。在你的例子中,PropertyChangedBase是父類games