我正在学习如何使用类周围的事件来通知 2 个类,如果一个类中发生偶数。我创建了以下内容。
namespace TestConsole
{
class Program : Form
{
public event EventHandler Something;
public Program()
{
Button btn = new Button();
btn.Parent = this;
btn.Text = "Click Me.!";
btn.Location = new Point(100, 100);
btn.Click += Btn_Click;
Something += HandleThis;
}
private void Btn_Click(object sender, EventArgs e)
{
Something(this,null);
}
private void HandleThis(object sender, EventArgs e)
{
Console.WriteLine("From Main: Something typed");
}
static void Main(string[] args)
{
Application.Run(new Program());
Console.ReadLine();
}
}
class One
{
One()
{
Program SubscriberObj = new Program();
SubscriberObj.Something += HandleEvent;
}
private void HandleEvent(object sender, EventArgs e)
{
Console.WriteLine("From One: Something typed");
}
}
class Two
{
Two()
{
Program SubscriberObj = new Program();
SubscriberObj.Something += HandleEvent;
}
private void HandleEvent(object sender, EventArgs e)
{
Console.WriteLine("From Two: Something typed");
}
}
}
我希望在单击按钮后触发第一类和第二类的 HandleEvent 方法。但我只看到在 Program 课程中引发的事件。如何做到这一点?