我正在将一些代码从VB.NET迁移到C#(3.5)。
我发现了以下结构:
Public Event DataLoaded(ByVal sender As Object, ByVal e As EventArgs)
Protected Sub Mag_Button_Load_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Mag_Button_Load.Click
[..]
RaiseEvent DataLoaded(Me, EventArgs.Empty)
End Sub
[..]
'Other Class
Private Sub LoadData(ByVal sender As Object, ByVal e As System.EventArgs) Handles oData.DataLoaded
[..]
End Sub
将此类行为转换为C#的最简单方法是什么?
答案 0 :(得分:11)
我建议使用Telerik Code Converter作为开头。
C#没有像VB.NET那样通过“Handles”关键字轻松自动附加事件处理程序。
//EventHandler declaration
public event EventHandler DataLoaded;
protected void Mag_Button_Load_Click(object sender, EventArgs e)
{
//Raise Event
if (DataLoaded != null) {
DataLoaded(this, EventArgs.Empty);
}
}
此外,您需要将事件处理程序分配给对象,如下所示:
Button1.Click += Button1_Click;
protected void Button1_Click(object sender, EventArgs e)
{
//do something.
}
然而,C#确实具有这样做的简洁能力:
Button1.Click += (sender, e)=>
{
//do something
}