公共变量不起作用

时间:2015-03-20 15:13:29

标签: asp.net vb.net

Public Class sample
  Public inta As Integer
  Protected Sub button1(sender As Object, e As EventArgs)
    inta = "2"
  End Sub

  Protected Sub button2(sender As Object, e As EventArgs)
    Response.Write(inta)
  End Sub
End Class

这是我的aspx背后的示例代码。它继续显示0而不是2.我的代码与此示例的唯一区别是button2处于模态对话框中。但是当我尝试使用这个简单的代码时,它仍然无效。我做错了什么?

2 个答案:

答案 0 :(得分:0)

您不需要我可以看到的Public变量,因此将范围限制为所需的最低值。你可以使用这样的属性:

Public Class sample

  Private Property IntA As Integer
    Get
      Return TryCast(Session("IntA"), Integer)
    End Get
    Set(value As Integer)
      Session("IntA") = value
    End Set
  End Property

  Protected Sub button1(sender As Object, e As EventArgs)
    IntA = 2
  End Sub

 Protected Sub button2(sender As Object, e As EventArgs)
   Response.Write(IntA.ToString)
 End Sub

End Class

答案 1 :(得分:0)

将变量inta声明为Shared

Public Shared inta As Integer