我能从内部类访问"secondary this"吗?

3

我有基础课程

abstract class Unit {
    Unit target;
    abstract class UnitAI {/*...*/}
}

从这些中,我得出了

class Infantry extends Unit {
    class InfantryAI extends UnitAI {/*...*/}
}

InfantryAI这个类是否可以获取到用于访问其周围类Infantry成员的次要(隐式)this?

具体来说,它需要确定其目标是否正在瞄准其周围的类Infantry,例如:

if (/*secondary_this.*/target.target == secondary_this)

或者,通常由另一个 Unit 完成。

@SotiriosDelimanolis 对外部类的引用;我想我应该使用术语outer this,而不是secondary this - Stefan Stanković
1
“封闭实例”也可以。 - Sotirios Delimanolis
@SotiriosDelimanolis 谢谢,我对正确的术语有点不清楚... 我搜索了“从内部类访问”,但只找到了与成员访问相关的问题,而不是对象引用。 - Stefan Stanković
1个回答

6

您可以通过在类名前面添加来访问外部 this

Infantry.this.target; //"this" of the Infantry class from inside InfantryAI
Unit.this.target; //"this" of the Unit class from inside UnitAI

然而,这并不适用于static嵌套类,因为它们不属于外部类的实例。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接