简体   繁体   English

如何添加对列表的引用

[英]How can I add a reference to a List

I thought that a List holds references of objects, so I thought I could create an object of my own custom class called "Node", add it to a list and then later delete the object by assigning it with null. 我以为列表可以保存对象的引用,所以我想可以创建自己的自定义类“节点”的对象,将其添加到列表中,然后再通过为对象分配空值来删除该对象。 (I know I could use remove from the list, but that's not what I want to do.) So when I print the list again, it still prints with the name of the object "testNode" even though I assigned it with null. (我知道我可以从列表中使用remove,但这不是我想要的。)因此,当我再次打印列表时,即使我将其分配为null,它仍会以对象“ testNode”的名称进行打印。 What can I do to add a reference to a list? 如何添加对列表的引用?

Node testNode = new Node("Name", id);
List<Node> listNodes = new List<Node>();
listNodes.Add(testNode);

for (int i = 0; i < listNodes.Count; i++)
    listNodes[i].ToString();

testNode = null;

for (int i = 0; i < listNodes.Count; i++)
    listNodes[i].ToString();

What you add to the list is a reference to that instance of Node . 您添加到列表中的是Node实例的引用 Not a referernce to your variable. 没有引用您的变量。

With

testNode = null;

you only assign null to your variable. 您只将null分配给变量。 This does nothing to the real instance testNode was referencing. 这无助于真正的实例testNode被引用。 And it does not change the list or remove the reference from the list. 并且它不会更改列表或从列表中删除引用

So the only way to remove the reference from the list is - well - Remove : 因此,从列表中删除引用的唯一方法是-很好- Remove

listNodes.Remove(testNode);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM