15

我已经看到ClassName.this在 SO 和其他在线地方的很多 Android 代码中使用(而不是简单的this关键字)来引用类的当前实例。我知道您可能决定以this类名开头以消除任何歧义,但根据我的经验,这样做通常是不必要的,因为实际上只能this指一件事——代码正在执行的类的当前实例. 还有什么我忽略的建议在this关键字前面加上一个类名总是更好的做法,或者在任何情况下它实际上是必要的?

4

4 回答 4

28

要从内部类或匿名类内部访问封闭类的实例,您需要使用以下语法:

EnclosingClass.this.someMethod();
于 2013-03-29T18:35:27.037 回答
10

这实际上只能指一件事。

这是不正确的。

还有什么我忽略的建议在 this 关键字前面加上类名总是更好的做法,或者是否有任何必要的情况?

是和是,分别。特别是,ClassName.this需要从内部类中获取this.

例如:

  myButton.setOnClickListener(new Button.OnClickListener() {  
    public void onClick(View v) {
          startActivity(new Intent(MyActivity.this, MyOtherActivity.class));
        }
     });

在这里,使用this而不是MyActivity.this将失败并出现编译错误,抱怨这Button.OnClickListener不是Intent构造函数的有效第一个参数。MyActivity.this返回包含该实例的this实例。MyActivityButton.OnClickListener

于 2013-03-29T18:38:18.553 回答
0

我没有那么多回购来发表评论,所以把它写下来作为答案。

我认为这个问题的基本关注点是检查在开发人员已经知道不会有任何内部类调用的情况下,使用 classname.this 而不是 'this' 关键字是否存在任何优势。

Of course in case of inner class scenarios ,you have to use classname.this to call its enclosing class. but there can be scenraio that you already know that this particular code won't be called inside any inner class.so why to specify classname.this,instead just use 'this'.

于 2014-10-24T04:27:35.540 回答
0

Window win = SwingUtilities.getWindowAncestor(RedPanel.this);

Usually you'll see code like this inside of an inner class. So say you have a class called RedPanel that subclasses a JPanel, and say inside of this you have an anonymous inner class that implements ActionListener. If you want to refer to the "this" RedPanel object inside of the ActionListener, you can't use just "this" since it refers to the ActionListener not to RedPanel. To get a handle on the RedPanel "this" you'll need to use RedPanel.this.

于 2018-06-05T19:36:46.157 回答