我有以下内容(简化以使其易于阅读)
头等舱:
Class MainWindow
Private mFile As myFile 'myFile is a class containing a bunch of stuff
Sub go()
dim editFiles as New EditFiles(mFile)
End Sub
End Class
二等舱:
Public Class EditFiles
Private mFile As myFile 'myFile is a class containing a bunch of stuff
Sub New(ByRef passedFile As myFile)
' This call is required by the designer.
InitializeComponent()
' Add any initialization after the InitializeComponent() call.
mFile = passedFile
End Sub
我想发生的是我在第二个类中对 mFile 所做的任何更改,以便在第一类中也更改 mFile,我认为通过在初始化中传递它 ByRef 会发生,但显然不会。
我想知道的是完成这项工作的合适方法是什么?我知道我可以创建一个全局变量,但必须有一种方法可以从第一个类传递 mFile 的指针,以便第二个类中的 mFile 本质上是相同的。
如果您可以通过编辑上面的代码向我展示一个简单的示例,我将不胜感激!
您应该在第二个类中创建第一个类的对象。此外,您还需要一个在第一个类中更改 mFile 值的方法。它应该是如下所示的内容。
Class MainWindow
Private mFile As myFile 'myFile is a class containing a bunch of stuff
Sub go()
dim editFiles as New EditFiles(mFile)
End Sub
sub setMFile(_mfile as myfile)
me.mfile = _mfile
End Class
二等舱
Public Class EditFiles
Private mFile As myFile 'myFile is a class containing a bunch of stuff
Sub New(ByRef passedFile As myFile)
' This call is required by the designer.
InitializeComponent()
' Add any initialization after the InitializeComponent() call.
mFile = passedFile
dim newObject as new MainWindow
newobject.setMFile(mFile)
End Sub
在将 MainWindow 的 mFile 变量传递给 EditFiles 对象之前,您需要确保该变量已初始化。
此外,如果 myFile 是一个类,你甚至不需要传递它 ByRef。
以下是我最终解决问题的方式:
Class MainWindow
Private mFile As myFile 'myFile is a class containing a bunch of stuff
Sub go()
dim editFiles as New EditFiles(me, mFile)
End Sub
sub setMFile(_mfile as myfile)
me.mfile = _mfile
End Class
二等舱
Public Class EditFiles
Private mainWindow As mainWindow
Private mFile as myFile
Sub New(ByVal sourceWindow As mainWindow, byVal sourceFile as myFile)
' This call is required by the designer.
InitializeComponent()
' Add any initialization after the InitializeComponent() call.
mainWindow = sourceWindow
mFile = sourceFile
end Sub
Sub setFile
mainWindow.setMFile(mFile)
End Sub