在类中删除此对象 [英] Delete this object inside the class

查看:142
本文介绍了在类中删除此对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

private class Node
{
    Item name;
    Node next;

    public void deleteObject()
    {
        this = null;
    }
}

是否可以删除类中的对象?我试图做上面的,但它给一个错误,左侧应该是一个变量。 节点是内部类。非常感谢。

Is it possible to delete object inside class? I am trying to do above, but it gives an error, that left-side should be a variable. Node is inner class. Thank you.

编辑
var1 当通过执行 var1 = null 删除 var1 时,c> var2

var1 and var2 has reference to the object of this class, when I delete var1 by doing var1 = null, I want that var2 would be deleted too.

推荐答案

,我想要 var2 p>不,这是不可能的。

No, that's not possible. Neither is it necessary.

对象从一个根对象无法访问时,将有资格进行垃圾回收(有效地释放)。基本上自引用并不重要。

The object will be eligible for garbage collection (effectively deallocated) as soon as it is not reachable from one of the root objects. Basically self-references doesn't matter.

只要确保你不会存储对象的引用,你不会再使用它,其余的将由垃圾处理

Just make sure you never store references to objects which you won't use any more and the rest will be handled by the garbage collector.

关于您的编辑:


var1和var2引用了这个类的对象,当我通过执行var1 = null删除var1时,我想要删除var2。

var1 and var2 has reference to the object of this class, when I delete var1 by doing var1 = null, I want that var2 would be deleted too.

您不能强制另一个对象删除其引用。你必须明确告诉其他对象这样做。例如,如果你正在实现一个链表(看起来像你的例子),我建议你添加一个 prev 引用,并做类似:

You can't force another object to drop its reference. You have to explicitly tell that other object to do so. For instance, if you're implementing a linked list (as it looks like in your example), I would suggest you add a prev reference and do something like:

if (prev != null)
    prev.setNext(next);  // make prev discard its reference to me (this).

if (next != null)
    next.setPrev(prev);  // make next discard its reference to me (this).

这篇关于在类中删除此对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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