简体   繁体   English

C#事件和委托

[英]C# event and delegate

I want to detach the custom event but could not detach. 我想分离自定义事件但无法分离。 Below I am using -= to detach the event. 下面我使用-=来分离事件。 I assume after this, the TextChanged2 method should not be invoked as I have unregistered the event. 我假设在此之后,不应该调用TextChanged2方法,因为我已取消注册该事件。 Is my understanding wrong? 我的理解错了吗?

public delegate void TextChangedEventHandler1(object sender, TextBoxargs ta);
public event TextChangedEventHandler1 TextChanged1;
private void textBox1_TextChanged(object sender, EventArgs e)
{
    this.TextChanged1 -= new  TextChangedEventHandler1(TextChanged2);
    TextChanged2(sender, e);
}

public void TextChanged2(object sender, EventArgs e)
{
    textBox1.Text = textBox1.Text.ToUpper();
}

What you are doing is right. 你在做什么是正确的。 But using the following line of the code you can detach the event handler. 但是使用以下代码行可以分离事件处理程序。

this.TextChanged1 -= new  TextChangedEventHandler1(TextChanged2);

But on the second line you called the function directly so that it called the textchange2 function: 但是在第二行你直接调用了函数,所以它调用了textchange2函数:

TextChanged2(sender, e);

I want to detach the custom event but could not detach. 我想分离自定义事件但无法分离。

You do. 你做。 You detach very well your event. 你很好地分离了你的活动。

TextChanged2 method should not be invoked as I have unregistered the event. 不应该调用TextChanged2方法,因为我已取消注册该事件。

It should not be invoked when this.textChanged1, but you invoke it yourself by calling TextChanged2(sender, e); 它不应该在this.textChanged1时调用,而是通过调用TextChanged2(sender, e); 自己调用它 TextChanged2(sender, e);

采用

this.TextChanged1 -= TextChanged2;

I suggest you give some more reasonable names to your methods, controls, and events. 我建议你给你的方法,控件和事件提供一些更合理的名字。 I could imagine half the confusion here stems from confusing names. 我可以想象这里混淆的一半源于令人困惑的名字。

For example, in one comment to an answer, you mention that if you don't call the TextChanged2 event handler (for the TextChanged1 event...) explicitly, it will never get called. 例如,在对答案的一个注释中,您提到如果您没有显式调用TextChanged2事件处理程序(对于TextChanged1事件...),它将永远不会被调用。 This would lead to the question when , and where , you raise the TextChanged1 event. 这将导致该问题何地 ,你提高TextChanged1事件。 If you have indeed subscribed the TextChanged2 handler to the TextChanged1 event with the += operator, then the handler will be invoked as soon as the event is raised. 如果你确实订阅了TextChanged2处理到TextChanged1与事件+=运算符,则该处理器尽快引发该事件被调用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM