该类型的封闭实例在范围内不可访问

12

我有这段代码:

Thread thread = new Thread(null, vieworders, "MagentoBackground");
thread.start();
m_progressDialog = ProgressDialog.show(SoftwarePassionView.this, 
    "Please wait...", "Retrieving data...", true);

出现以下编译错误:

在范围内无法访问SoftwarePassionView类型的封闭实例

这是什么原因导致的?如何解决?


5
这段代码是在SoftwarePassionView类内部还是它的子类中? - MByD
3个回答

11
表达式SoftwarePassionView.this只有在非静态的内部/嵌套类中找到示例代码,并且其中一个封闭类是SoftwarePassionView时才有意义。它表示“给我封闭的SoftwarePassionView实例”。
如果此代码不在该上下文中(正如编译器错误所指示的那样),则需要用普通变量名称或方法调用替换表达式,以给出对某个SoftwarePassionView对象的引用。
为了记录,这里有一个示例,SoftwarePassionView.this在其中不会导致编译错误:
public class SoftwarePassionView {

    public class Inner {
        ...
        public void doIt() {
            Thread thread = new Thread(null, vieworders, "MagentoBackground");
            thread.start();
            m_progressDialog = ProgressDialog.show(SoftwarePassionView.this, 
                  "Please wait...", "Retrieving data...", true);
        }
    }
}

我确实不确定你在说什么。能否给一个例子?还有这是一个非静态内部的。 - Christian

6

4
如果你想将代码片段放在除 SoftwarePassionView 之外的另一个类中,你可以在线程构造函数中传递 SoftwarePassionView 类的实例。
以下是一个示例:
Class SoftwarePassionView {
  ....

  Thread thread = new something(SoftwarePassionView);
  thread.start();
  ......
  }

在另一个类中

 Class something extends Thread{
  SoftwarePassionView SPV;
  something(SoftwarePassionView){
  super(null, vieworders, "MagentoBackground");
  this.SPV = SoftwarePassionView}
  }

   @Override
public void run(){
    m_progressDialog = ProgressDialog.show(SPV, 
    "Please wait...", "Retrieving data...", true);
     }

  }

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