我正在c#中学习自定义事件处理程序。
为此目的,我创建了一个 ChangePropertyEventArgs 类,并从 EventArgs 继承它,如下所示
ChangePropertyEventArgs
class ChangePropertyEventArgs : EventArgs
{
public bool status = false;
public ChangePropertyEventArgs(bool value) {
this.status = value;
}
}
我创建了一个Adress类并在其中放置一个字段地址..
我想在Adress提交的Adress申请被更改
时提出这个事件地址类
class Adress
{
//Property that is going to change
private string address;
public string Address
{
get { return address; }
set { address = value;
ChangePropertyEventArgs e = new ChangePropertyEventArgs(true);
ChangePropertEventHandler handler = changeEvent;
changeEvent(this, e);
//changeEvent.Invoke(null,e);
}
}
//Delegate used for event
public delegate void ChangePropertEventHandler(object sender, ChangePropertyEventArgs e);
//Event Declared in publisher class
public event ChangePropertEventHandler changeEvent;
}
最后,我点击按钮
在Windows窗体应用程序中调用该事件 private void button1_Click(object sender, EventArgs e)
{
Adress a = new Adress();
a.Address = textBox1.Text;
a.changeEvent += a_changeEvent;
}
void a_changeEvent(object sender, ChangePropertyEventArgs e)
{
// ChangePropertyEventArgs e1 = (ChangePropertyEventArgs)sender;
//MessageBox.Show(e.status.ToString());
}
但是代码在行中出现了错误
changeEvent(this, e);
错误:对象引用未设置为对象的实例。