Say you have the following design:
ClassA
ClassC
ClassB
Property: object of type ClassA
Property: object of type ClassC
If ClassB
has an object of type ClassA
, is there any way for ClassA
to be able to access members of ClassB
? In other words, say there is a method of ClassA
(say ClassA.GetVegetables()
) but that ClassA
method needs to access ClassB
's property of type ClassC
, is that possible?
Looks like you are mixing 2 concepts together:
Whether or not ClassA can call any method of ClassB depends on whether ClassA has a reference to ClassB (first concept). This can be achieved by passing an instance of ClassB to ClassA's constructor for example.
Once ClassA has a reference to an instance of ClassB, it can only access methods of ClassB that are marked public
. Look up access modifiers
for more information.
Without seeing any aditional code the best way to approach is by simply passing the required information as an argument to your GetVegetables
method.
Ideally you should pass all the required data as an argument to make the methods very self-contained without relying on some global state.
This is assuming the current design is optimal; this might be solved just as fine by changing the design details but we can't tell without seeing more code.
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.