开发者

What is the difference between events in VB and C#?

开发者 https://www.devze.com 2022-12-24 22:43 出处:网络
I am a VB programmer working my way into C#. I learned how to create and raise events in vb and am finding that it isnt done t开发者_如何学Pythonhe same way in C#. Has anybody come across an article t

I am a VB programmer working my way into C#. I learned how to create and raise events in vb and am finding that it isnt done t开发者_如何学Pythonhe same way in C#. Has anybody come across an article that will help me to understand how to do events in C# and maybe explain why it is different in VB.

Thanks


Does this help?

VB.NET vs. C# - Delegates / Events


The main difference is the syntax that's used. Underneath, they use the exact same mechanisms within the CLR.

However, VB.NET provides special syntax via WithEvents and Handles, allowing you to do:

Dim WithEvents button1 As Button

Private Sub button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyButton.Click 
    ' Handle button click
End Sub

C# doesn't provide an equivelent - all events must be explicitly subscribed to via event +=, which is more like VB.NET's AddHandler statement.


The difference is mostly syntactic.

See this handy reference about the differences.

The event handler in VB.NET is declared with the Handling key word appended to the event handler signature. In C# you need to use register it with +=.

In VB.NET you invoke the event with RaiseEvent, in C# you call the delegate directly.


Reading from:

http://msdn.microsoft.com/en-us/library/aa645739(VS.71).aspx

An event in C# is a way for a class to provide notifications to clients of that class when some interesting thing happens to an object. The most familiar use for events is in graphical user interfaces; typically, the classes that represent controls in the interface have events that are notified when the user does something to the control (for example, click a button).

Events, however, need not be used only for graphical interfaces. Events provide a generally useful way for objects to signal state changes that may be useful to clients of that object. Events are an important building block for creating classes that can be reused in a large number of different programs.

Refer to the article for the rest.


A good quick general reference for some key differences in syntax can be found here. Search for "events" to get to that section.

Key differences is that VB requires you to use some keywords rather than addition/subtraction to wire up events, but gives you a handles keyword automatically wire a routine to an event. And when passing a delegate, you must use a pointless AddressOf keyword. (Sorry for the editorial, but I think that keyword causes more confusion than it saves!)

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号