如何访问外部类的字段,给定对内部类的对象的引用?外部类的访问字段
class Outer
{
int field;
class Inner
{
void method(Inner parameter)
{
// working on the current instance is easy :)
field = 0;
Outer.this.field = 1;
// working on another instance is hard :(
parameter.field = 2; // does not compile
parameter.Outer.this.field = 3; // does not compile
parameter.outer().field = 4; // This works...
}
// ...but I really don't want to have to write this method!
Outer outer()
{
return Outer.this;
}
}
}
我也试过Outer.parameter.field
和许多其他变种。有没有一种语法可以做我想要的?
不是一个内部类被用来只是其外部类中的目的是什么? – Heisenbug
我认为这是做到这一点的方法。如果你觉得这是错误的,也许你可以考虑重构或以不同的方式构建这些类。 – Luciano
我不知道有任何其他的方式来做到这一点,但我会说,如果你必须这样做扭曲,通常意味着你应该重新考虑设计。 –