2017-02-16 95 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