访问父级对象

Access Parent level object

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人时,我想将sports子变量更新为10。

问题:如何访问父 class 并更新运动 class 变量?

您需要创建 Activity 的实例。还需要在里面初始化_Sports

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

或者使用对象诱人

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

activity._Sports.sub = 10;

顺便说一下,Activity 不是 sports 的父 class。 Activity 持有 sports 对象作为成员。在您的示例中,PropertyChangedBasegames 的父级 class。

您可以使用一个事件向 Activity class 发出更新时间的信号。

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 class 中,您可以在构造函数中注册事件并将必要的更新写入事件处理程序。在你的情况下低于 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"));
            }                
        }
    }          
}

并在Activityclass构造函数中再次注册事件:

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 会自动更新。希望能帮助到你。当然还有其他方法可以完成此更新。这是我第一个想到的