c# – Wrapping List.Add()给出 – 对象引用未设置为对象的实例

前端之家收集整理的这篇文章主要介绍了c# – Wrapping List.Add()给出 – 对象引用未设置为对象的实例前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我想用自定义类包装List类.至于现在我有这样的事情;
  1. public class PriorityListOfNodes
  2. {
  3.  
  4. private List<Node> list_;
  5. private IComparer<Node> sorter_;
  6.  
  7. public List<Node> List_ {
  8. get {return list_;}
  9. set {list_ = value;}
  10. }
  11.  
  12. public PriorityListOfNodes ()
  13. {
  14. sorter_ = new NodeSorter_fValueDescending ();
  15. }
  16.  
  17. public Node PopFromEnd ()
  18. {
  19. Node temp = new Node (list_ [list_.Count - 1]);
  20. list_.RemoveAt (list_.Count - 1);
  21. return temp;
  22. }
  23.  
  24. public Node PeekFromEnd ()
  25. {
  26. return list_ [list_.Count - 1];
  27. }
  28.  
  29. public void Add (ref Node toAdd)
  30. {
  31. Debug.Log (toAdd);
  32. list_.Add (toAdd);
  33. list_.Sort (sorter_);
  34. }
  35. }

我什么时候做

  1. Node temp = new Node(10,20); //custom constructor
  2. PriorityListOfNodes l = new PriorityListOfNodes();
  3. l.add(temp);

我得到运行时异常:

Object reference not set to an instance of an object

我也试过没有参考,但结果相同.我在这做错了什么?

解决方法

您永远不会实际实例化List< Node>.
  1. public PriorityListOfNodes ()
  2. {
  3. sorter_ = new NodeSorter_fValueDescending ();
  4. list_ = new List<Node>();
  5. }

猜你在找的C#相关文章