vb.net main不允许设置私有变量

时间:2012-10-04 00:07:59

标签: vb.net variables scope main

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

Public Class Form1

<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

结束班

1 个答案:

答案 0 :(得分:2)

因为在VB中'Shared'类似于C#中的'static'。而且您正在尝试对对象的实例进行静态引用。

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

MSDN VB Shared Sope