gpt4 book ai didi

C# 类实例通讯

转载 作者:太空狗 更新时间:2023-10-29 21:15:42 25 4
gpt4 key购买 nike

例如,当您有同一类的不同实例时,例如“FootballTeam”,并且您想让此 FootballTeam 类的另一个实例知道发生了什么事解决这个问题的最佳方法是什么?

我猜事件不会真正起作用......

如:

FootballTeam A = new FootballTeam();
FootballTeam B = new FootballTeam();

// now A needs to let B know about it's manager change
// manager is a property inside this class...

最佳答案

事件可以工作:

FootballTeam A = new FootballTeam();
FootballTeam B = new FootballTeam();
A.ManagerChanged += B.OnOtherManagerChanged;

事件的定义——FootballTeam 在其 Manager 属性更改值时调用其 OnManagerChanged 方法:

class FootballTeam
{
public event EventHandler ManagerChanged;

protected virtual void OnManagerChanged(EventArgs e)
{
EventHandler handler = ManagerChanged;
if (handler != null)
handler(this, e);
}

public void OnOtherManagerChanged(object sender, EventArgs e)
{
FootballTeam otherTeam = (FootballTeam) sender;
// A manager changed on a different FootballTeam instance
// ...do something here
}
}

关于C# 类实例通讯,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1882763/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com