[英]Accessing Parent Class Properties from Property Objects
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
? 如果
ClassB
具有类型为ClassA
的对象,那么ClassA
是否可以访问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? 换句话说,假设有一个
ClassA
方法(例如ClassA.GetVegetables()
),但ClassA
方法需要访问ClassB
类型的ClassC
属性,这可能吗?
Looks like you are mixing 2 concepts together: 看起来您正在将2个概念混合在一起:
Whether or not ClassA can call any method of ClassB depends on whether ClassA has a reference to ClassB (first concept). ClassA是否可以调用ClassB的任何方法取决于ClassA是否引用ClassB(第一个概念)。 This can be achieved by passing an instance of ClassB to ClassA's constructor for example.
例如,可以通过将ClassB的实例传递给ClassA的构造函数来实现。
Once ClassA has a reference to an instance of ClassB, it can only access methods of ClassB that are marked public
. 一旦ClassA引用了ClassB的实例,它就只能访问标记为
public
的ClassB的方法。 Look up access modifiers
for more information. 查找
access modifiers
以获取更多信息。
Without seeing any aditional code the best way to approach is by simply passing the required information as an argument to your GetVegetables
method. 在没有看到任何附加代码的情况下,最好的处理方法是将所需信息作为参数传递给
GetVegetables
方法。
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.
可以通过更改设计细节来解决此问题,但是如果看不到更多代码,我们就无法分辨。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.