Sae*_*ani 0 c# events delegates winforms
我有一个名字的winform应用程序myForm
.在这个表格中我打开另一个表格:
private OtherForm otherForm; //this is a field
private OpenOtherForm()
{
if (otherForm == null)
{
otherForm = new OtherForm();
otherForm.FormClosing += delegate { MessageBox.Show("OtherForm will be closed"); otherForm = null};
}
MessageBox.Show("Form is already active!");
}
Run Code Online (Sandbox Code Playgroud)
这很好用.但我也有第二种形式的方法.我想尝试捕获你的电话.
例如,如果在第二个表单中调用OtherForm.DoSomething(),我想要一个消息框来显示thi.
我试图分配OtherForm.DoSomething() += delegate { /* mesagebox */};
但是这不会编译
otherForm.FormClosing += delegate { .. }
正在编译因为FormClosing是Event类型.可以订阅一个事件,当它被解雇时,您的代码将会运行.
您不能在类似的方法上使用此语法DoSomething()
.只能使用类似的方法调用方法otherForm.DoSomething()
.DoSomething()
然后将执行代码.
但是,您可以创建自己的事件,并在第二种形式执行DoSomething()时触发它.
它会是这样的:
public event EventHandler RaiseCustomEvent;
public void DoSomething()
{
OnRaiseCustomEvent();
}
protected virtual void OnRaiseCustomEvent()
{
EventHandler handler = RaiseCustomEvent;
if (handler != null)
{
handler(this, EventArgs.Empty););
}
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
288 次 |
最近记录: |