在阅读有关事件的在线教程后,我想我几乎知道发生了什么。我开发了以下非常简单的代码来在值大于 5 的情况下触发事件。我知道代码非常无用,但我正在使用它来表达我的观点。(而不是主我只是使用按钮事件来触发代码。)
//declare the delegate
public delegate void MyDelegate(string str);
public class SomeClass
{
public event MyDelegate MyEventFromDelegate;
private int i;
public int I
{
get
{ return i; }
set
{
if (value > 5)
{
MyEventFromDelegate("Value Greater than 5");
i = 0;
}
else
{
i = value;
}
}
}
}
public partial class Form1 : Form
{
public Form1()
{ InitializeComponent(); }
public void Method_To_Call(String rx)
{ MessageBox.Show("This method will be called if greater than 5");}
private void button1_Click(object sender, EventArgs e)
{
SomeClass a = new SomeClass();
a.MyEventFromDelegate +=new MyDelegate(Method_To_Call);
a.I = 12;
}
}
我在这里唯一担心的是当我们想用声明引发事件时
MyEventFromDelegate("Value Greater than 5");
如果稍后(在按钮单击事件中)我们实际上要为它分配一个函数,以便在每次触发事件时调用,那么将参数传递给事件的关键是此时。