简体   繁体   中英

Accessing Properties of one Object from another Object

I'm new to object oriented programming. I have two classes in class-modules:

ClassA

Public Time As Double

ClassB

Public Sub Progress()
    ClassAObject.Time = 5
End Sub

This is the code running in the subroutine

Public Sub Progressing()
    Dim ClassAObject As New ClassA
    Dim ClassBObject As New ClassB
    Call ClassBObject.Progress
End Sub

The subroutine ClassBObject.Progress seem to not be able to access ObjectA . I think how I refer to the object might be wrong. How do I fix this?

Class B does not know of class A. There are many ways to do this, but one way is to make the .Progress() sub take an input.

Code in ClassA:

Public Time As Double

Code in ClassB:

Public Sub Progress(ClassAObject As ClassA)
    'Assuming that you have a .Time property in ClassAObject
    ClassAObject.Time = 5
End Sub

Code in Main:

Sub Main()
    Dim ClassAObject As New ClassA
    Dim ClassBObject As New ClassB
    ClassBObject.Progress ClassAObject
End Sub

You could pass an instance of ClassA to the Progress method. So for example:

Change Progress method to:

Public Sub Progress(a As ClassA)
    a.Time = 5
End Sub

And call it like this:

Public Sub Progressing()
    Dim ClassAObject As New ClassA
    Dim ClassBObject As New ClassB
    Call ClassBObject.Progress(ClassAObject) ' <--- pass instance of ClassA
End Sub

I would recommend giving your classes and objects more descriptive names, even if you're just practicing. It will make it easier for you and others to read and understand your code. For example, Dim apple As New Fruit is always easier to understand than Dim ClassAObject As New ClassA .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM