将“句柄”从 VB.NET 迁移到 C#
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/794332/
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
Migrating 'Handles' from VB.NET to C#
提问by pistacchio
I'm migrating some code from VB.NET to C# (3.5).
我正在将一些代码从 VB.NET 迁移到 C# (3.5)。
I find structures like:
我发现结构如下:
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
What is the most straightforward way to translate such behaviour to C#?
将此类行为转换为 C# 的最直接方法是什么?
采纳答案by Jose Basilio
I recommend using the Telerik Code Converteras a start.
我建议使用Telerik Code Converter作为开始。
C# does not have that easy automatic attaching of event handlers by means of the "Handles" keyword like VB.NET does.
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);
}
}
Also, You need to assign your event handlers to the objects like this:
此外,您需要将事件处理程序分配给这样的对象:
Button1.Click += Button1_Click;
protected void Button1_Click(object sender, EventArgs e)
{
//do something.
}
However C# does have the succinct ability of doing this as well:
但是,C# 也确实具有这样做的简洁能力:
Button1.Click += (sender, e)=>
{
//do something
}