VB.NET WithEvents关键字的行为 - VB.NET编译器的限制? [英] VB.NET WithEvents keyword behavior - VB.NET compiler restriction?

查看:195
本文介绍了VB.NET WithEvents关键字的行为 - VB.NET编译器的限制?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的工作变得像熟悉C#,因为我用VB.NET(我的工作场所使用的语言)。一个关于学习过程的最好的事情是,通过学习对方的语言你会了解您的主要语言 - 像这样的小问题弹出:

I'm working on becoming as familiar with C# as I am with VB.NET (the language used at my workplace). One of the best things about the learning process is that by learning about the other language you tend to learn more about your primary language--little questions like this pop up:

据我已经找到了来源,和过去的经验,被声明为的 WithEvents就的是能够引发事件的VB.NET场。据我所知,C#不具有直接等效 - 但我的问题是:字段的没有的这个关键字在VB.NET不能引发事件,有没有一种方法来创建在C#中同样的行为呢?是否VB编译器根本不必处理它们的事件阻止这些对象(而实际上使他们能够引发事件像往常一样)?

According to the sources I've found, and past experience, a field in VB.NET that is declared as WithEvents is capable of raising events. I understand that C# doesn't have a direct equivalent--but my question is: fields without this keyword in VB.NET cannot raise events, is there a way to create this same behavior in C#? Does the VB compiler simply block these objects from having their events handled (while actually allowing them to raise events as usual)?

我只是好奇;我没有对这个问题的任何特定的应用程序...

I'm just curious; I don't have any particular application for the question...

推荐答案

省略WithEvents就不会从引发事件阻止成员。它只是阻止你使用他们的活动的手柄关键字。

Omitting WithEvents doesn't block members from raising events. It just stops you from using the 'handles' keyword on their events.

下面是一个典型的使用WithEvents就的:

Here is a typical use of WithEvents:

Class C1
    Public WithEvents ev As New EventThrower()
    Public Sub catcher() Handles ev.event
        Debug.print("Event")
    End Sub
End Class

下面是不使用WithEvents就和近似等于一类。这说明了为什么WithEvents就相当有用的:

Here is a class which doesn't use WithEvents and is approximately equivalent. It demonstrates why WithEvents is quite useful:

Class C2
    Private _ev As EventThrower
    Public Property ev() As EventThrower

        Get
            Return _ev
        End Get

        Set(ByVal value As EventThrower)
            If _ev IsNot Nothing Then
                    removehandler _ev.event, addressof catcher
            End If
            _ev = value
            If _ev IsNot Nothing Then
                    addhandler _ev.event, addressof catcher
            End If
        End Set
    End Property

    Public Sub New()
        ev = New EventThrower()
    End Sub

    Public Sub catcher()
        Debug.print("Event")
    End Sub
End Class

这篇关于VB.NET WithEvents关键字的行为 - VB.NET编译器的限制?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆