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으로 업데이트하고 싶습니다.
질문 : 부모 클래스에 액세스하고 스포츠 클래스 변수를 업데이트하려면 어떻게해야합니까?
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
자동으로 업데이트됩니다. 도움이 되었기를 바랍니다. 물론이 업데이트를 수행하는 다른 방법이 있습니다. 내 마음에 처음 떠오른
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다