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.
问题:如何访问父类并更新体育类变量?
答案 0 :(得分:0)
您需要创建Activity
的实例。您还需要在其中初始化_Sports
Activity activity = new Activity();
activity._Sports = new sports();
activity._Sports.sub = 10;
或使用object tantalizer
Activity activity = new Activity
{
_Sports = new sports()
};
activity._Sports.sub = 10;
顺便说一下,Activity
不是sports
的父类。 Activity
将sports
个对象作为成员。在您的示例中,PropertyChangedBase
是games
的父类。
答案 1 :(得分: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
会自动更新。希望能帮助到你。当然还有其他方法可以完成此更新。这是我想到的第一个