我想用我的自定义类包装List
类。至于现在我有这样的事情;
public class PriorityListOfNodes
{
private List<Node> list_;
private IComparer<Node> sorter_;
public List<Node> List_ {
get {return list_;}
set {list_ = value;}
}
public PriorityListOfNodes ()
{
sorter_ = new NodeSorter_fValueDescending ();
}
public Node PopFromEnd ()
{
Node temp = new Node (list_ [list_.Count - 1]);
list_.RemoveAt (list_.Count - 1);
return temp;
}
public Node PeekFromEnd ()
{
return list_ [list_.Count - 1];
}
public void Add (ref Node toAdd)
{
Debug.Log (toAdd);
list_.Add (toAdd);
list_.Sort (sorter_);
}
}
我现在这样做
Node temp = new Node(10,20); //custom constructor
PriorityListOfNodes l = new PriorityListOfNodes();
l.add(temp);
我得到运行时异常:
对象引用未设置为对象的实例
我也试过没有ref
,但结果相同。我在这里做错了什么?
答案 0 :(得分:9)
您实际上从未实例化List<Node>
。
public PriorityListOfNodes ()
{
sorter_ = new NodeSorter_fValueDescending ();
list_ = new List<Node>();
}
答案 1 :(得分:1)
默认情况下,类具有空的无参数构造函数,因此您实际上具有:
public class PriorityListOfNodes
{
private List<Node> list_;
// ...
public PriorityListOfNodes()
{
}
// ...
}
当您稍后调用Add
时,您的列表已声明,但未初始化。您需要在某些时候执行此操作,可能在构造函数中:
public class PriorityListOfNodes
{
private List<Node> list_;
// ...
public PriorityListOfNodes()
{
this.list_ = new List<Node>();
// ...
}
// ...
}