Pergunta

When ever I try to change an attribute in the load method of a class I created, it won't let me open it. If I leave the load method blank or put anything else there, it works fine.

Public Class Main

    'SHIPS
    Dim AirCraftCarrier As Ship

    Private Sub Main_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        AirCraftCarrier.name = "ACC"                                                                        ' These won't work
        AirCraftCarrier.SetAttributes("ACC", AirCraftCarrier_image, 5, "vertical", new_pos, False, False)   ' If I leave it blank or keep anything else here, it opens fine.

    End Sub
End Class
Public Class Ship
    Public name As String
    Public image As PictureBox
    Public direction As String
    Public selection As Boolean
    Public placed As Boolean
    Public location(2) As Integer

    Public Sub SetAttributes(ByVal name1 As String, ByVal image1 As PictureBox, ByVal length1 As Integer, ByVal direction1 As String, ByVal location1 As Array, ByVal selected1 As Boolean, ByVal placed1 As Boolean)
        name = name1
        image = image1
        direction = direction1
        selection = selected1
        placed = placed1

        location(0) = location1(0)
        location(1) = location1(1)
    End Sub
End Class
Foi útil?

Solução

First changes to Ship. Classes tend to use Properties rather than fields:

Public Class Ship
    Public Property name As String
    Public Property image As PictureBox    ' bad name; Net has an Image class
    ' etc

   ' set essential props via the constructor:
   Public Sub New(sName As String, picB As PictureBox)
      name = sName
      image = picB
   End Sub

Then in main for creating it:

Public Class Main

    Dim AirCraftCarrier As Ship     ' this is just a variable declaration

    Private Sub Main_Load(ByVal sender As System.Object, 
            ByVal e As System.EventArgs) Handles MyBase.Load

        ' Create an instance: 
        AirCraftCarrier = New Ship("ACC", frm.PicBoxName)  

        ' set other properties
        AirCraftCarrier.Direction = "SSW"
        AirCraftCarrier.Foo = "Bar"

    End Sub
End Class

With a constructor you can pass the essential information, like the unique name to the class when you create it. This is used instead of the SetAttributes sub.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top