是否可以在类中设置一个类的实例为null [英] Is it possible to set to null an instance of a class within the class

查看:80
本文介绍了是否可以在类中设置一个类的实例为null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在类中将类的实例设置为null。例如,我可以做这样的事情吗?

pre $ int main {
//创建一个新的测试对象
Test test = new Test();
//删除该对象。此方法应该将对象test设置为null,
//因此可以由垃圾收集器调用它。
test.delete();




public class Test {

public delete(){
this = null;
}
}

我已经试过了,它不起作用。使用this = null我得到左侧需要变量的错误。有没有办法实现类似的东西?

解决方案

一个对象的实例不知道哪个引用可能引用它,所以没有办法在对象可以将这些引用归零。你要求的是不可能的(*)。



* 至少不是不添加一堆脚手架来跟踪所有参考,并以某种方式告知他们的主人,他们应该被禁止 - 绝不会是仅仅为了方便。


Is it possible to set to null an instance of a class within the class. For example, could I do something like this

int main{
    //Create a new test object
    Test test = new Test();
    //Delete that object. This method should set the object "test" to null, 
    //thus allowing it to be called by the garbage collector.
    test.delete();

}


public class Test{

    public delete(){
        this = null;
    }
}

I have tried this and it does not work. Using "this = null" I get the error that the left hand side needs to be a variable. Is there a way to achieve something similar?

解决方案

An instance of an object doesn't know which references might be referring to it, so there's no way that code within the object can null those references. What you're asking for isn't possible(*).

* at least not without adding a pile of scaffolding to keep track of all the references, and somehow inform their owners that they should be nulled - in no way would it be "Just for convenience".

这篇关于是否可以在类中设置一个类的实例为null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆