0

我有以下代码 - 我想在开始之前预设/初始化子程序中的一些变量。(具体来说,我会读取一个控制文件并预加载一些变量,比如起始文件夹搜索路径)。我该怎么做呢?

公开课形式1

<STAThread()> _
Shared Sub Main()
    Dim mainWindow As Form1 = New Form1()
    MessageBox.Show("Hello! I'm exectuing!")


    ' This next line generates an error.
    ' I don't know how to set this variable in Main. 
    ' How do I set up variables, perhaps from a control file ?
    openFileDialog1.InitialDirectory = "c:\mypath"

    Application.Run(mainWindow)

End Sub
Private Sub FindButton_Click(ByVal sender As System.Object, _
           ByVal e As System.EventArgs) Handles FindButton.Click

    ' Displays an OpenFileDialog so the user can select a Cursor.
    Dim openFileDialog1 As New OpenFileDialog()
    ' Filter by All Files
    openFileDialog1.Filter = "All Files|*.*"

    openFileDialog1.Title = "Process a File"


    If openFileDialog1.ShowDialog() = DialogResult.OK Then
        If openFileDialog1.CheckPathExists Then
            If openFileDialog1.CheckFileExists Then
                ' do stuff with the file here 

        Else
            StatusLabel.Text = "Path does not exist"
        End If
    Else
        StatusLabel.Text = "openFileDialog1.ShowDialog error"
    End If


End Sub

结束类

4

1 回答 1

2

因为在 VB 中,“共享”类似于 C# 中的“静态”。而且您正在尝试对对象的实例进行静态引用。

那就是openFileDialog1.InitialDirectory = "c:\mypath"试图引用 openFileDialog1 对象实例。将该行移到 Form1 的构造函数(或者可能是其他更合适的事件,oninit 或我不熟悉 winforms 的东西),它应该完成同样的事情。

MSDN VB 共享 Sope

于 2012-10-04T00:33:45.060 回答