オブザーバー パターンとデリゲートを理解しようとする助けが必要です。このコードを別の Web サイトで見つけたので、実際に何をしているのかを理解しようとしています。誰か助けてくれませんか。
コードを実行すると、"Server is up and running" と "Server is down, We are working on it it will be back soon" の両方のメッセージが表示されます。Main には server.ServerStatus = true; があるため、両方のメッセージを受け取っていると思います。および server.ServerStatus = false です。ただし、server.ServerStatus = true; をコメントアウトすると、実行すると、「サーバーは稼働中です」というメッセージが表示されますが、「サーバーがダウンしています。まもなく復旧します。」というメッセージしか表示されないと予想していました。誰か説明できますか?スーザン
class Program
{
static void Main(string[] args)
{
Server server = new Server();
server.ServerStatusChanged += new EventHandler(ProcessServerStatus);
server.ServerStatus = true;
server.ServerStatus = false;
Console.Read();
}
public class Server
{
public event EventHandler ServerStatusChanged;
private bool _ServerStatus;
public bool ServerStatus
{
get { return this._ServerStatus; }
set {
if (this._ServerStatus == value) return; // Dont need to do anything;
if (this.ServerStatusChanged != null) // make sure the invocation list is not empty
ServerStatusChanged(value, new EventArgs()); // Firing Event
this._ServerStatus = value;
}
}
}
public static void ProcessServerStatus(object sender, EventArgs e)
{
bool status = (bool)sender;
if (status)
Console.WriteLine("Server is up and running");
else
Console.WriteLine("Server is down, We are working on it it will be back soon");
}
}