在对象中引发的事件也会在同一类的另一个对象中触发



VB . NET 2010, Framework 3.5

试着理解为什么会这样。我从同一个Class1创建了两个对象。GlobalClass1具有全局作用域,LocalClass1具有模块作用域。

在UControl的Load事件中,我设置了LocalClass1 = GlobalClass1从这一点上,任何时候我改变GlobalClass1.TestProperty的值,属性值也在LocalClass1中更新。当GlobalClass1事件触发时,LocalClass1中的Events被触发。

这是我正在寻找的结果=>能够在其他几个类模块和用户控件中有一个全局对象的事件。

我不太明白为什么简单地设置本地对象=全局对象导致本地对象自动更新它的属性值时,全局对象的属性更新或为什么本地事件自动触发时,全局对象引发的事件?

Module Module1
    Public WithEvents frm As New MainForm
    Public WithEvents GlobalClass1 As New Class1
    Public Sub Main()
        frm.Init()
       frm.ShowDialog()
   End Sub
End Module

Public Class MainForm
    Private uiUserControl As UControl
    Public Function Init() As Boolean
        uiUserControl = New UControl
        uiUserControl.Location = New System.Drawing.Point(60, 80)
        Me.Controls.Add(uiUserControl)
        Return True
    End Function
    Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
        Static count As Integer
        GlobalClass1.TestProperty = count.ToString ' This line propagates to the Private Local LocalClass1 and cause it's event to fire??
        count += 1
    End Sub
End Class

Public Class UControl
    Private WithEvents LocalClass1 As New Class1
    Private Sub UControl_Load(sender As Object, e As System.EventArgs) Handles Me.Load
        LocalClass1 = GlobalClass1
    End Sub
    Private Sub LocalClass1_TestPropertyChanged() Handles LocalClass1.TestEvent
        Me.TextBox1.Text = LocalClass1.TestProperty  'This Event fires when events are raised in the other object => GlobalClass1??
    End Sub
End Class

Public Class Class1
    Public Event TestEvent()
    Private _testProperty As String
    Public Property TestProperty() As String
        Get
            Return _testProperty
        End Get
        Set(ByVal value As String)
            _testProperty = value
            RaiseEvent TestEvent()
        End Set
    End Property
End Class

类实例(对象)都引用堆上分配给它们的相同内存空间。

from comments:

问题出在这一行:LocalClass1 = GlobalClass1

它们一开始是不同的对象,但后来你让它们指代同一事物。对象引用(或引用类型)与值类型(如integer)的工作方式不同:

Dim x As Int32
Dim y As Int32 = 42
x = y

作为值类型,y的值被赋给x。引用类型本质上是指针的包装器或别名。因此,您的赋值代码将指向New Class1的原始指针替换为已赋值给GlobalClass1的指针

在MSDN阅读更多关于值与引用类型的信息

相关内容

  • 没有找到相关文章

最新更新