2

我有以下内容(简化以使其易于阅读)

头等舱:

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 基本相同。

如果您可以通过编辑上面的代码向我展示一个简单的示例,我将不胜感激!

4

3 回答 3

3

您应该在第二类中创建第一类的对象。您还需要一种方法来更改第一类中 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
于 2012-11-20T19:01:44.917 回答
2

您需要确保在将 MainWindow 的 mFile 变量传递给 EditFiles 对象之前对其进行初始化。

此外,如果 myFile 是一个类,您甚至不需要通过 ByRef 传递它。

于 2012-11-20T19:30:55.037 回答
1

这是我最终解决问题的方法:

 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
于 2012-11-21T13:32:49.280 回答