如何在VB.NET中有两个类的实例

时间:2013-11-24 02:27:33

标签: vb.net winforms class variables

我创建了一个类,并希望创建此类的两个单独实例。我已经能够在Web应用程序中实现这一点,但我试图在Windows窗体中执行此操作,出于某种原因,当我创建类的第二个实例时,它具有来自第一个实例的可变数据。

我试图将这两个实例创建为全局变量,因为我希望它们可以通过单独的子例程来访问。这两个实例声明如下:

Public Class Form1
    Dim oTree1_Animation As New clsAnimation()
    Dim oTree2_Animation As New clsAnimation()

然后我尝试在一个子例程中填充实例,该子例程触发MouseDown事件:

Private Sub PictureBox1_MouseDown(sender As System.Object, e As System.EventArgs) Handles PictureBox1.MouseDown
    Dim oFrame As New clsFrame(2, {0, -32}, {0, 0})
    Dim timTimer As New Timer()
    oTree1_Animation.Initialise(2, 100, oFrame, PictureBox1, timTimer)
    oTree1_Animation.AnimationStart()
End Sub

然后以类似的方式填充第二个:

Private Sub PictureBox2_MouseDown(sender As System.Object, e As System.EventArgs) Handles PictureBox2.MouseDown
    Dim oFrame As New clsFrame(2, {0, -32}, {0, 0})
    Dim timTimer As New Timer()
    oTree2_Animation.Initialise(2, 100, oFrame, PictureBox2, timTimer)
    oTree2_Animation.AnimationStart()
End Sub

该课程如下:

Public Class clsAnimation
    Public Event Tick As EventHandler

    Public Shared FrameCount As Integer
    Public Shared FrameInterval As Integer
    Public Shared CurrentFrame As Integer = 0
    Public Shared FrameSet As clsFrame
    Public Shared Image As PictureBox
    Public Shared WithEvents Timer As Timer

    ''' <summary>
    ''' Creates an empty instance of the Animation class
    ''' </summary>
    ''' <remarks></remarks>
    Public Sub New()
    End Sub

    ''' <summary>
    ''' Creates a new instance of the Animation class and preloads it with variables
    ''' </summary>
    ''' <param name="iFrameCount">Number of frames in this animation as Integer</param>
    ''' <param name="iFrameInterval">Frame transition speed (milliseconds) as Integer</param>
    ''' <param name="clsFrameSet">Frame information as clsFrame</param>
    ''' <param name="imgImage">The picturebox that we're animating as PictureBox</param>
    ''' <remarks></remarks>
    Public Sub Initialise(ByVal iFrameCount As Integer, ByVal iFrameInterval As Integer, ByVal clsFrameSet As clsFrame, ByRef imgImage As PictureBox, ByRef timTimer As Timer)
        FrameCount = iFrameCount
        FrameInterval = iFrameInterval
        FrameSet = clsFrameSet
        Image = imgImage
        Timer = timTimer

        Timer.Interval = FrameInterval
    End Sub

但是,oTree1_Animation和oTree2_Animation都共享相同的变量。我不知道我是否遗漏了一些小东西,或者我只是想以一种不可能的方式使用课程,对此的任何帮助都会非常感激。

1 个答案:

答案 0 :(得分:4)

您必须从所有类变量中删除SharedShared表示值在此类的所有实例之间共享。

这通常被称为“静态”(但出于某种原因,VB.NET使用不同的术语)。

有关Microsoft的解释,请参阅MSDN(感谢benjineer)。