Как сделать массивы объектов в VB.net? - PullRequest
0 голосов
/ 26 мая 2018

Я не могу отладить это.

Моя процедура создания массива неправильная?

Отображаемая ошибка:

System.NullReferenceException: 'Ссылка на объект не установлена ​​для экземпляра объекта '

Module Module1

Class Toy
    Private Name, ID As String
    Private Price As Single
    Private MinimumAge As Integer
    Dim Count As Integer

    Public Sub New()

    End Sub

    Public Sub SetName(ByVal N As String)
        Name = N
    End Sub

    Public Sub SetID(ByVal I As String)
        'VALIDATION CHECK FOR ID !
        While Len(I) < 4
            Console.WriteLine("Kindly Enter the ID with Lenght of Max 4 Characters")
        End While
        ID = I
    End Sub

    Public Sub SetPrice(ByVal SP As Single)
        Price = SP
    End Sub

    Public Sub SetUserAge(ByVal SM As Integer)
        'VALIDATION CHECK FOR AGE
        While SM < 0 Or SM < 18
            Console.WriteLine("Minimum age is 18")
        End While
        MinimumAge = SM
    End Sub

    Public Function GetName()
        Return Name(Count)
    End Function

    Public Function GetID()
        Return ID
    End Function

    Public Function GetPrice()
        Return Price
    End Function

    Public Function GetAge()
        Return MinimumAge
    End Function

End Class

Class ComputerGame
    Inherits Toy
    Private Category, Consol As String

    Public Sub New()
    End Sub

    Public Sub SetConsole(ByVal C As String)
        While C <> "PS4" Or C <> "XBOX"
            Console.WriteLine("Invalid console entered")
        End While
        Consol = C
    End Sub

    Public Sub SetCategory(ByVal SC As String)
        Category = SC
    End Sub

    Public Function GetConsole()
        Return Consol
    End Function

    Public Function GetCategory()
        Return Category
    End Function

End Class

Class Vehicle
    Inherits Toy
    Private Type As String
    Private Length, Height, Weight As Single

    Public Sub New()
    End Sub

    Public Sub SetType(ByVal TY As String)
        While TY <> "Car" Or TY <> "Bus" Or TY <> "Truck"
            Console.WriteLine("vehicle is not in list !")
        End While
        Type = TY
    End Sub

    Public Sub SetLength(ByVal SL As Single)
        Length = SL
    End Sub

    Public Sub SetHeight(ByVal SH As Single)
        Height = SH
    End Sub

    Public Sub SetWeight(ByVal SW As Integer)
        Weight = SW
    End Sub

    Public Function GetT()
        Return Type
    End Function

    Public Function GetLength()
        Return Length
    End Function

    Public Function GetHeight()
        Return Height
    End Function

    Public Function GetWeight()
        Return Weight
    End Function

End Class

Sub Main()
    Dim ThisGame(6) As Toy
    ThisGame(6) = New Toy
    ThisGame(1).SetID("23456a")
    ThisGame(2).SetID("236789b")
    Console.WriteLine(ThisGame(1).GetID)

    Console.ReadKey()

End Sub

End Module

1 Ответ

0 голосов
/ 26 мая 2018

Вот так должен выглядеть ваш класс Toy, используя длинный метод Properties.Обратите внимание, что у вас есть Открытые Свойства и личное поле для хранения значений (иногда называемое полем поддержки). Каждое Свойство имеет процедуру Get и Set, в которую вы можете добавить свой проверочный код.

Public Class Toy

    Private _Name As String
    Public Property Name As String
        Get
            Return _Name
        End Get
        Set(value As String)
            _Name = value
        End Set
    End Property

    Private _ID As String
    Public Property ID As String
        Get
            Return _ID
        End Get
        Set(value As String)
            If value.Length < 4 Then
                Console.WriteLine("Kindly Enter the ID with Lenght of Max 4 Characters")
                Exit Property
            End If
            _ID = value
        End Set
    End Property

    Private _Price As Single
    Public Property Price As Single
        Get
            Return _Price
        End Get
        Set(value As Single)
            _Price = value
        End Set
    End Property

    Private _MinimumAge As Integer
    Public Property MinimumAge As Integer
        Get
            Return _MinimumAge
        End Get
        Set(value As Integer)
            If value < 0 Or value < 18 Then
                Console.WriteLine("Minimum age is 18")
                Exit Property
            End If
            _MinimumAge = value
        End Set
    End Property

    Private _Count As Integer
    Public Property Count As Integer
        Get
            Return _Count
        End Get
        Set(value As Integer)
            _Count = value
        End Set
    End Property

End Class

Текущие версии имеютАвтоматические свойства, где компилятор предоставляет поля getter, setter и backer.Обратите внимание, что вы все еще можете написать свой собственный Get и Set, где вам нужно добавить код.

Public Class Toy
    Public Property Name As String
    Public Property Price As Single
    Public Property Count As Integer

    Private _ID As String
    Public Property ID As String
        Get
            Return _ID
        End Get
        Set(value As String)
            If value.Length < 4 Then
                Console.WriteLine("Kindly Enter the ID with Lenght of Max 4 Characters")
                Exit Property
            End If
            _ID = value
        End Set
    End Property

    Private _MinimumAge As Integer
    Public Property MinimumAge As Integer
        Get
            Return _MinimumAge
        End Get
        Set(value As Integer)
            If value < 0 Or value < 18 Then
                Console.WriteLine("Minimum age is 18")
                Exit Property
            End If
            _MinimumAge = value
        End Set
    End Property

End Class

Пожалуйста, прочитайте комментарии в строке относительно вашего массива.

Sub Main()
        Dim ThisGame(6) As Toy 'You are defining and array with 7 elements of Toy
        'Each element is Nothing at this point and you will get a null exception error if you
        'try to access an element.
        ThisGame(6) = New Toy 'Here you have created an instance of your class for the 7th element
        'The other six elements are still nothing so the next 3 lines will get 
        'NullReferenceException: 'Object reference not set to an instance of an object.' 
        'ThisGame(1).ID = "23456a"
        'ThisGame(2).ID = "236789b"
        ThisGame(1) = New Toy
        ThisGame(1).ID = "23456a"
        ThisGame(2) = New Toy
        ThisGame(2).ID = "236789b"
        'Remember the first element in you array is ThisGame(0)
        Console.WriteLine(ThisGame(1).ID)

        Console.ReadKey()

    End Sub
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...