Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/vb.net/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
将表单定义为变量vb.net_Vb.net_Forms_Variables - Fatal编程技术网

将表单定义为变量vb.net

将表单定义为变量vb.net,vb.net,forms,variables,Vb.net,Forms,Variables,如果您想在Form2中插入一个变量,我使用这个 Dim Variable As New Form2 但是如果我有两种形式的同名函数,我会使用if if 1 = 1 Then Dim Variable As New Form2 Else Dim Variable As New Form3 End If 这很好,但是如果我在下面的代码中开始使用这个变量,如果我在没有条件的情况下使用,就会发生错误,一切都很好,在条件似乎明白该怎么做时使用 Variable.DataGridVi

如果您想在Form2中插入一个变量,我使用这个

Dim Variable As New Form2
但是如果我有两种形式的同名函数,我会使用if

if 1 = 1 Then
     Dim Variable As New Form2
Else
     Dim Variable As New Form3
End If
这很好,但是如果我在下面的代码中开始使用这个变量,如果我在没有条件的情况下使用,就会发生错误,一切都很好,在条件似乎明白该怎么做时使用

Variable.DataGridView1.Rows.Add(row)
对象引用未设置为对象的实例


您需要首先声明变量,然后将其指定给特定类型:

Dim Variable As Form = Nothing
If 1 = 1 Then
   Variable = New Form2()
Else
   Variable = New Form3()
End If
但通常情况下,您会采用面向对象的方法,通过每个表单实现一个公共接口来实现这一点

然后,您可以执行以下操作:

Dim Variable As IForm
If 1 = 1 Then
   Variable = New Form2() 'Form2 implements IForm
Else
   Variable = New Form3() 'Form3 implements IForm
End If

创建一个局部范围的变量,不再设置全局
变量的值
dim
去掉,即:
variable=New Form3()
您最好已经有了一个form2和Form3变量,只需根据条件使用所需的变量即可。
If
语句创建了一个新的块作用域-其中声明的任何内容都将只存在于该块作用域中…这样做的原因是为了避免您的下一个问题:如何判断变量是Form2还是Form3?