简体   繁体   English

C#对象突然为空

[英]C# Object suddenly null

I've searched so long and hard for this and now I'm at road's end. 我为此进行了漫长而艰苦的搜索,而现在我已经走到了尽头。 I've had this issue with more than this project, but I ended up scrapping the others. 除了这个项目,我还遇到了其他问题,但最终我还是放弃了其他项目。 I have a code (C#) which is basically me trying to do Huffman tree. 我有一个代码(C#),基本上是我想要做的霍夫曼树的代码。 At one point I do this ("nodeList" is List(Node)): 有一点我做到了(“ nodeList”是List(Node)):

Node node = new Node(nodeList[0], nodeList[1]);
nodeList.Add(node); // Adds a new node which includes two subnodes.

// Remove nodes from list (as they are now included in another node)
nodeList.RemoveAt(0);
nodeList.RemoveAt(1);

And the constructors in use here is: 这里使用的构造函数是:

// Constructor that takes nodes
public Node(Node left, Node right)
{
   leftNode = new Node(left);
   rightNode = new Node(right);
}

// Constructor that only takes 1 single node
public Node(Node copy)
{
   rightNode = copy.rightNode;
   leftNode = copy.leftNode;
   unencodedBits = copy.unencodedBits;
   encodingValue = copy.encodingValue;
   positions = copy.positions;
}

I did the second constructor as a hope that it would fix my problem (thinking that removing the node from the list maybe nulled it out.) (all of the values in my Node-class is on the right side of the second constructor.) 我做了第二个构造函数,希望它能解决我的问题(认为从列表中删除该节点可能会使它无效。)(Node类中的所有值都在第二个构造函数的右侧。)

The problem: After doing the second "RemoveAt" the Node will no longer contain the two nodes. 问题:执行完第二个“ RemoveAt”后,节点将不再包含两个节点。 And I can not understand why. 而且我不明白为什么。 What do I have to do to prevent this from happening and why does it happen (so I can understand similar cases in the future)? 我必须采取什么措施来防止这种情况发生以及为什么发生(这样我以后才能理解类似的情况)?

I probably forgot to include some vital information; 我可能忘记了一些重要的信息。 If I did, please tell me. 如果我这样做了,请告诉我。 And thanks for any assistance. 并感谢您的协助。

Is your nodeList object in array or a List? 您的nodeList对象是数组还是List? If it is a list, then nodeList.RemoveAt(0) causes the node currently located and index 1 to now be located at index 0. so you would need to call 如果它是一个列表,则nodeList.RemoveAt(0)导致当前定位的节点和索引1现在位于索引0。因此,您需要调用

nodeList.RemoveAt(0); 
nodeList.RemoveAt(0); 

instead of 代替

nodeList.RemoveAt(0); 
nodeList.RemoveAt(1);

see here: http://msdn.microsoft.com/en-us/library/5cw9x18z(v=vs.110).aspx 看到这里: http : //msdn.microsoft.com/zh-cn/library/5cw9x18z(v=vs.110).aspx

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

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