访问父级对象

时间:2017-02-16 07:11:42

标签: c# parent-child inotifypropertychanged

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 个答案:

答案 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的父类。 Activitysports个对象作为成员。在您的示例中,PropertyChangedBasegames的父类。

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