VB NET 2010,Framework 3.5
试着理解为什么会这样。我从同一个Class1创建了两个对象。 GlobalClass1
使用全局范围,LocalClass1
使用模块范围。
在UControl的加载事件中,我设置LocalClass1 = GlobalClass1
从此时开始,我更改GlobalClass1.TestProperty
的值时,属性值也会在LocalClass1
中更新。触发GlobalClass1事件时触发LocalClass1中的事件。
这是我正在寻找的结果=>能够在其他几个类模块和用户控件中触发全局对象的事件。
我不太明白为什么简单地设置Local Object = Global Object会导致Local Object在更新Global Object属性时自动更新它的属性值,或者为什么Local Events会在Global Object正在举办此活动?
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
答案 0 :(得分:1)
类实例(对象)都引用堆上分配给它们的相同内存空间。
答案 1 :(得分:1)
来自评论:
问题在于这一行:LocalClass1 = GlobalClass1
他们从不同的对象开始,但后来你让他们引用了同样的东西。对象引用 - 或引用类型 - 的工作方式与整数:
之类的值类型不同Dim x As Int32
Dim y As Int32 = 42
x = y
作为值类型,y的值分配给x。引用类型本质上是指针的包装或别名。因此,您的分配代码将原始指针替换为New Class1
,指针已分配给GlobalClass1
在MSDN上阅读有关Value vs Reference types的更多信息