我有一个类,其中一个方法调用嵌套类.我想从嵌套类中访问父类属性.
public class ParentClass
{
private x;
private y;
private z;
something.something = new ChildClass();
public class ChildClass
{
// need to get x, y and z;
}
}
Run Code Online (Sandbox Code Playgroud)
如何从子类中访问x,y和z?与引用父类有关,但如何做?
使用this
关键字将对"self"的引用传递给ChildClass的构造函数.
public class ParentClass
{
public X;
public Y;
public Z;
// give the ChildClass instance a reference to this ParentClass instance
ChildClass cc = new ChildClass(this);
public class ChildClass
{
private ParentClass _pc;
public ChildClass(ParentClass pc) {
_pc = pc;
}
// need to get X, Y and Z;
public void GetValues() {
myX = _pc.X
...
}
}
}
Run Code Online (Sandbox Code Playgroud)