为共享变量分配值?

时间:2016-02-07 03:18:17

标签: vb.net string nullreferenceexception shared public

我需要帮助为我制作的公共共享变量赋值。

Public Shared craftability As String = "Craftable"
Private Sub CheckBox1_CheckedChanged(sender As Object, e As EventArgs) Handles CheckBox1.CheckedChanged
    If CheckBox1.Checked = True Then
        craftability = "Non-Craftable"
    Else
        craftability = "Craftable"
    End If

当我尝试使用我在另一个子类中分配给它的值时,它说:

变量'craftability'在赋值之前使用。在运行时可能会产生空引用异常。

并返回一个空值。

1 个答案:

答案 0 :(得分:0)

看起来你已经在类之外声明了一个共享变量。共享变量仅由类的实例使用。例如,如果您想跟踪一个类的实例数,您可以在类中声明一个共享变量,如此控制台应用程序

Sub Main()
    Dim t1 As New testclass
    Dim t2 As New testclass
    Console.WriteLine(t2.Count)
    Console.ReadKey()
End Sub

Private Class testclass
    Private Shared instanceCount As Integer

    Public Sub New()
        instanceCount += 1
    End Sub

    Public ReadOnly Property Count
        Get
            Return instanceCount
        End Get
    End Property
End Class

您最终将 2 写入控制台。并且共享变量只能由TestClass的每个实例访问。

OK静态变量就像在过程中声明的局部变量一样。但是对于常规局部变量,当过程完成时,局部变量将被销毁。静态变量继续存在并保留其最新值。下次调用相同的过程时,静态变量不会再次声明并重新初始化,因为它仍然存在并包含您分配给它的最新值。静态变量仅在销毁定义的类或模块时销毁。

所以你的代码应该是

Private Sub CheckBox1_CheckedChanged(sender As Object, e As EventArgs) Handles CheckBox1.CheckedChanged
   Static Dim craftability As String = "Craftable"
    If CheckBox1.Checked = True Then
        craftability = "Non-Craftable"
    Else
        craftability = "Craftable"
    End If

但是,查看您提供的代码,如果您想在整个课程中使用 craftability ,那么只需按照您已经完成的方式声明它 - 在子外部,但没有< strong>共享关键字。如果不知道你希望如何使用 craftability ,我恐怕不能更准确。希望这有帮助