- = new EventHandler(Method)与 - =方法 当方法作为参数传递时有什么区别?
为什么removeNew无法取消订阅?
看下面的课:
public class Class1
{
public EventHandler _eh;
public void OnEvent()
{
if (_eh != null)
{
_eh.Invoke("", new EventArgs());
}
}
public void remove(EventHandler evHandler)
{
// unsubscribe successfully
_eh -= evHandler;
}
public void removeNew(EventHandler evHandler)
{
// failed to unsubscribe
_eh -= new EventHandler(evHandler);
}
}
Run Code Online (Sandbox Code Playgroud)
更新:
@SchabseLaks,只是为了清除我的查询我正在添加调用此方法的代码:
public partial class Form1 : Form
{
Class1 c1 = new Class1();
public Form1()
{
InitializeComponent();
c1._eh += Hello;
}
private void button1_Click(object sender, EventArgs e)
{
c1.OnEvent();
}
private void Hello(object sender, EventArgs e)
{
MessageBox.Show("hello");
}
private void button2_Click(object sender, EventArgs e)
{
c1.removeNew(Hello);
}
private void button3_Click(object sender, EventArgs e)
{
c1.remove(Hello);
}
}
Run Code Online (Sandbox Code Playgroud)
委托只能从方法创建.
new EventHandler(evHandler)是简写new EventHandler(evHandler.Invoke),因为Invoke是实际调用委托的任何委托类型的方法.
由于你_eh没有evHandler.Invoke作为处理程序,所以什么都不做.
| 归档时间: |
|
| 查看次数: |
902 次 |
| 最近记录: |