C# 如何使用 addHandler 引发事件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1488573/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to raise event using addHandler
提问by Mitesh
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.
我对 Vb.Net 事件和处理程序很满意。任何人都可以帮助我如何在 c# 中创建事件处理程序,并引发事件。
回答by tster
public MyClass()
{
InitializeComponent();
textBox1.LostFocus += new EventHandler(testBox1_LostFocus);
}
void testBox1_LostFocus(object sender, EventArgs e)
{
// do stuff
}
回答by Andrew Hare
In C# 2 and up you add event handlers like this:
在 C# 2 及更高版本中,您可以添加如下事件处理程序:
yourObject.Event += someMethodGroup;
Where the signature of someMethodGroup
matches the delegate signature of yourObject.Event
.
其中 的签名someMethodGroup
与 的委托签名相匹配yourObject.Event
。
In C# 1 you need to explicitly create an event handler like this:
在 C# 1 中,您需要像这样显式地创建一个事件处理程序:
yourObject.Event += new EventHandler(someMethodGroup);
and now the signatures of the method group, event, and EventHandler
must match.
现在方法组、事件和EventHandler
必须匹配的签名。
回答by MarkJ
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#.
只知道 C#,或者只知道 VB.Net 的开发者可能不知道,这是 VB.NET 和 C# 之间较大的差异之一。
I will shamelesssly copythis nice explanation of VB events: VB uses a declarative syntax for attaching events. The Handlesclause 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 WithEventsmodifier appearing on the declaration of the underlying variable such as a button. You can also attach property handlers using the AddHandlerkeyword, and remove them with RemoveHandler. For example
我将无耻地复制VB 事件的这个很好的解释:VB 使用声明性语法来附加事件。该手柄条款出现在将处理该事件的代码。在适当的时候,多个方法可以处理同一个事件,多个事件可以由同一个方法处理。Handles 子句的使用依赖于出现在底层变量(如按钮)声明中的WithEvents修饰符。您还可以使用AddHandler关键字附加属性处理程序,并使用 RemoveHandler 删除它们。例如
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:
在 C# 中,您不能使用声明性语法。您使用 += 重载以充当 VB.Net AddHandler。这是从tster 的回答中无耻地窃取的示例:
public MyClass()
{
InitializeComponent();
textBox1.Leave += new EventHandler(testBox1_Leave);
}
void testBox1_Leave(object sender, EventArgs e)
{
//Do Stuff
}