如何使用addHandler来引发事件 [英] How to raise event using addHandler
问题描述
任何人都可以帮助我如何在c#中创建事件处理程序,并引发事件。
开发人员知道只有C#,或者只是VB.Net,可能不知道这是VB.NET和C#之间更大的区别之一。
我将无耻的复制 VB事件的这个很好的解释:VB使用声明性语法来附加事件。在处理事件的代码上会出现句柄子句。适当时,多个方法可以处理相同的事件,并且可以通过相同的方法来处理多个事件。使用Handles子句依赖于声明中出现的 WithEvents 修饰符的基础变量,如按钮。您还可以使用 AddHandler 关键字附加属性处理程序,并将其删除与RemoveHandler。例如
Friend WithEvents TextBox1 As System.Windows.Forms.TextBox
Private Sub TextBox1_Leave(ByVal发件人As System.Object,_
ByVal e As System.EventArgs)Handles TextBox1.Leave
'Do Stuff'
End Sub
在C#中,您不能使用声明式语法。你使用+ =这是重载的行为像VB.Net AddHandler。以下是 tster's answer 无耻的一个例子:
public MyClass()
{
InitializeComponent();
textBox1.Leave + = new EventHandler(testBox1_Leave);
}
void testBox1_Leave(object sender,EventArgs e)
{
// Do Stuff
}
I am comfortable with Vb.Net events and handlers. Can anybody will help me with how to create event handlers in c#, and raise events.
Developers who know only C#, or only VB.Net, may not know that this is one of the larger differences between VB.NET and C#.
I will shamelesssly copy this nice explanation of VB events: VB uses a declarative syntax for attaching events. The Handles clause appears on the code that will handle the event. When appropriate, multiple methods can handle the same event, and multiple events can be handled by the same method. Use of the Handles clause relies on the WithEvents modifier appearing on the declaration of the underlying variable such as a button. You can also attach property handlers using the AddHandler keyword, and remove them with RemoveHandler. For example
Friend WithEvents TextBox1 As System.Windows.Forms.TextBox
Private Sub TextBox1_Leave(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles TextBox1.Leave
'Do Stuff '
End Sub
In C# you can't use the declarative syntax. You use += which is overloaded to act like the VB.Net AddHandler. Here's an example shamelessly stolen from tster's answer:
public MyClass()
{
InitializeComponent();
textBox1.Leave += new EventHandler(testBox1_Leave);
}
void testBox1_Leave(object sender, EventArgs e)
{
//Do Stuff
}
这篇关于如何使用addHandler来引发事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!