我正在尝试实现排序列表。我已经创建了我想存储在列表中的类,但是由于某种原因,当我尝试运行 sort 方法时,我得到了一个异常抛出。似乎幕后的某些东西正在将null
引用传递给CompareTo
我已实现的方法。
这是我认为相关的代码。
数据对象定义如下:
namespace PrioritisedRequestQueue
{
public class XactTask : IComparable<XactTask>
{
public int priority;
public DateTime submitted;
public string name;
public XactTask( int priority, DateTime submitted, string name)
{
this.priority = priority;
this.submitted = submitted;
this.name = name;
}
public int CompareTo(XactTask rhs )
{
//EXCEPTION OCCURS HERE AFTER A NULL RHS HAS BEEN PASSED IN**
Console.WriteLine("comparing " + rhs.priority+"to "+this.priority);
if (rhs.priority <= this.priority)
{
Console.WriteLine("Entered first if");
Console.WriteLine("comparing " + rhs.submitted + "to " +
this.submitted);
if (rhs.submitted <= this.submitted)
{
Console.WriteLine("Entered second if");
return 1;
}
else
{
return -1;
}
}
else
{
Console.WriteLine("In else");
return -1;
}
}
}
}
保存列表的类定义如下:
namespace PrioritisedRequestQueue
{
public class Class1
{
public List<XactTask> tasks;
public Class1()
{
tasks = new List<XactTask>();
}
public void sort()
{
tasks.Sort();
}
public void add(XactTask task)
{
tasks.Add(task);
}
}
}
这是我用来进行测试的程序:
PrioritisedRequestQueue.Class1 tester = new PrioritisedRequestQueue.Class1();
tester.add(new PrioritisedRequestQueue.XactTask(1, DateTime.Now, "test1"));
tester.add(new PrioritisedRequestQueue.XactTask(1, DateTime.Now, "test2"));
Console.WriteLine(tester.tasks[0].name);
Console.WriteLine(tester.tasks[1].name);
tester.tasks.Sort();
测试程序的输出是:
comparing 1to 1 Entered first if
comparing 16/05/2011 14:41:57to 16/05/2011 14:41:57
Entered second if
comparing 1to 1 Entered first if
comparing 16/05/2011 14:41:57to 16/05/2011 14:41:57
Entered second if
comparing 1to 1
Entered first if
comparing 16/05/2011 14:41:57to 16/05/2011 14:41:57
Entered second if
comparing 1to 1
Entered first if
comparing 16/05/2011 14:41:57to 16/05/2011 14:41:57
Entered second if
然后它似乎将一个rhs 对象传递给 compare 方法,当它尝试访问 rhs 的优先级时null
我得到一个。NullReferenceException
你能告诉我为什么会发生这种情况以及我必须做些什么来解决这个问题吗?
如果您需要更多信息,请告诉我。