vb.net 什么是 Visual Basic withevents 和 C# 中的句柄

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31694011/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 19:20:52  来源:igfitidea点击:

what is the equivalent of visual basic withevents and handles in C#

c#vb.neteventstimerhandles

提问by Emrah KONDUR

I try to convert a Visual Basic (VB) project to C# and I have no idea how to change some of codes below,

我尝试将 Visual Basic (VB) 项目转换为 C#,但我不知道如何更改下面的一些代码,

In a windows form a field and a Timer object defined like this;

在一个窗口中形成一个字段和一个像这样定义的 Timer 对象;

Public WithEvents tim As New Timer
...
Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tim.Tick
End Sub
...

How to rewrite this lines in C#?

如何在 C# 中重写这一行?

回答by Guillermo Jimenez

In C# you enrol an EventHandlerby registering a method delegate with the event using the +=operator as follows:

在 C# 中,您可以EventHandler通过使用+=运算符向事件注册方法委托来注册一个,如下所示:

public Timer tim = new Timer();
tim.Tick += Timer1_Tick;

private void Timer1_Tick(object sender, EventArgs e)
{
   // Event handling code here
} 

This works because the Tickevent of the Timerclass implements an Eventas follows:

这是有效的,因为类的Tick事件Timer实现Event如下:

public event EventHandler Tick

and EventHandleris a method delegate with signature:

并且EventHandler是一个带有签名的方法委托:

public delegate void EventHandler(
    Object sender,
    EventArgs e
)

which is why any method that conforms to the EventHandlersignature can be used as a handler.

这就是为什么任何符合EventHandler签名的方法都可以用作处理程序的原因。