如何从vb.net中的另一个类引用类变量

时间:2012-11-20 18:03:11

标签: vb.net byref

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

头等舱:

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

如果您可以通过编辑上面的代码向我展示一个简单的例子,我真的很感激它!

3 个答案:

答案 0 :(得分:2)

您应该在第二个类中创建第一个类的对象。您还需要一种方法来更改第一个类中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

答案 1 :(得分:2)

你需要确保MainWindow的mFile变量在之前被>传递给EditFiles对象。

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

答案 2 :(得分: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