事件处理C#和VB.NET之间的差异主要体现在语法和编程习惯上。以下是两者之间的主要差异:
C#:
public class EventHandlerExample
{
public event EventHandler<CustomEventArgs> CustomEvent;
protected virtual void OnCustomEvent(CustomEventArgs e)
{
CustomEvent?.Invoke(this, e);
}
}
VB.NET:
Public Class EventHandlerExample
Public Event CustomEvent As EventHandler(Of CustomEventArgs)
Protected Overridable Sub OnCustomEvent(e As CustomEventArgs)
RaiseEvent CustomEvent(Me, e)
End Sub
End Class
C#:
public class EventHandlerExample
{
public event EventHandler<CustomEventArgs> CustomEvent;
protected virtual void OnCustomEvent(CustomEventArgs e)
{
CustomEvent?.Invoke(this, e);
}
}
public class CustomEventArgs : EventArgs
{
public string Message { get; set; }
}
public class EventHandlerExampleUsage
{
public EventHandlerExampleUsage()
{
EventHandlerExample example = new EventHandlerExample();
example.CustomEvent += Example_CustomEvent;
}
private void Example_CustomEvent(object sender, CustomEventArgs e)
{
Console.WriteLine(e.Message);
}
}
VB.NET:
Public Class EventHandlerExample
Public Event CustomEvent As EventHandler(Of CustomEventArgs)
Protected Overridable Sub OnCustomEvent(e As CustomEventArgs)
RaiseEvent CustomEvent(Me, e)
End Sub
End Class
Public Class CustomEventArgs
Inherits EventArgs
Public Property Message As String
End Class
Public Class EventHandlerExampleUsage
Public Sub New()
Dim example As New EventHandlerExample()
AddHandler example.CustomEvent, AddressOf Example_CustomEvent
End Sub
Private Sub Example_CustomEvent(sender As Object, e As CustomEventArgs)
Console.WriteLine(e.Message)
End Sub
End Class
C#:
public class EventHandlerExample
{
public event EventHandler<CustomEventArgs> CustomEvent;
protected virtual void OnCustomEvent(CustomEventArgs e)
{
CustomEvent?.Invoke(this, e);
}
public void TriggerEvent()
{
OnCustomEvent(new CustomEventArgs { Message = "Hello from C#!" });
}
}
VB.NET:
Public Class EventHandlerExample
Public Event CustomEvent As EventHandler(Of CustomEventArgs)
Protected Overridable Sub OnCustomEvent(e As CustomEventArgs)
RaiseEvent CustomEvent(Me, e)
End Sub
Public Sub TriggerEvent()
OnCustomEvent(New CustomEventArgs With {.Message = "Hello from VB.NET!"})
End Sub
End Class
总结:
C#和VB.NET在事件处理方面的差异主要体现在语法上,包括事件定义、事件处理器的注册和触发等。虽然两者在语法上有所不同,但是在事件处理的核心思想上是一致的。
领取专属 10元无门槛券
手把手带您无忧上云