What's the difference between this and Activity.this

在StackOverFlow寻找问题时,发现一个好东西,也是一直困扰自己的小bug。其实是很基础的东西啦。
引用http://stackoverflow.com/questions/10102151/whats-the-difference-between-this-and-activity-this

For example:
Intent intent = new Intent(this, SecondActivity.class);

eclipse error: The method setClass(Context, Class) in the type Intent is not applicable for the arguments (FirstActivity.ClickEvent, Class)

Intent intent = new Intent(FirstActivity.this, SecondActivity.class);

But that will be correct. Anybody can explain the difference between those two ? Thanks.
最高票答案:
this
refers to your current object. In your case you must have implemented the intent in an inner class ClickEvent, and thats what it points to.
Activity.this
points to the instance of the Activity you are currently in.

翻译过来就是this是你当前对象的引用,在你的例子中你肯定在内部类ClickEvent里面实现intent,他指向的是ClickEvent,而不是你要传入的Activity。
Activity.this指向你所填写的Activity名字的一个实例,也是引用。
总结:
this作为当前对象,直接用在Activity里面是没问题的,当this在匿名内部类中使用,当前的对象就变成new的内部类,而你传入的东西如果是整个Activity的话,就要Activity.this了。

所以保险起见,还是统一用Activity.this比较好。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 9,980评论 0 23
  • 每座城市里的青春都不是你所能熟悉的,正如这世界千千万万的人不是每一个人都是你所熟悉的。 可是总会有那...
    袋子别爱者阅读 388评论 0 0
  • 1、概述2、isa ,SEL,IMP, Method 关系3、消息机制 以及消息转发机制4、runtime的使用场...
    雪_晟阅读 279评论 0 1
  • 文/潮生 曾经沧海难为水,除却巫山不是云。你不是我又怎知我不爱你。前世的五百次回眸,都只为今生的相遇。茫茫人海,谁...
    潮生小编阅读 336评论 0 0