内部クラスのオブジェクトへの参照がある場合、外部クラスのフィールドにアクセスするにはどうすればよいですか?外部クラスのフィールドへのアクセス
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
それ以外の方法はわかりませんが、そのような曲げをする必要がある場合は、通常、デザインを再考する必要があると言います。 –