我对重载运算符仍然很陌生。在遇到这个问题之前,我认为我做得很好。在 != 运算符上引发 NullReferenceException。我假设它在 CompareTo 方法中使用它,但我不完全确定。如果有人能指出我正确的方向,我将不胜感激。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
List<Task> tasks = new List<Task>();
tasks.Add(new Task( "first", DateTime.Now.AddHours(2)));
tasks.Add(new Task( "second", DateTime.Now.AddHours(4)));
tasks.TrimExcess();
tasks.Sort();
}
}
public class Task : IComparable
{
public Task()
{
}
public Task(string nameIn, DateTime dueIn)
{
nameOfTask = nameIn;
dateDue = dueIn;
}
DateTime dateDue;
string nameOfTask;
public static bool operator <(Task t1, Task t2)
{
return (t1.dateDue < t2.dateDue);
}
public static bool operator >(Task t1, Task t2)
{
return (t1.dateDue > t2.dateDue);
}
public static bool operator ==(Task t1, Task t2)
{
return (t1.dateDue == t2.dateDue);
}
public static bool operator !=(Task t1, Task t2)
{
return (t1.dateDue != t2.dateDue);
}
public override int GetHashCode()
{
return Int32.Parse(this.dateDue.ToString("yyyymmddhhmmss"));
}
public override bool Equals(System.Object obj)
{
if (obj == null) return false;
Task t = obj as Task;
if ((System.Object)t == null) return false;
return (this.dateDue == t.dateDue);
}
int IComparable.CompareTo(object obj)
{
if (obj == null) return 1;
Task t = obj as Task;
if (t != null)
{
return this.dateDue.CompareTo(t.dateDue);
}
else
throw new ArgumentException("Object is not a Task");
}
}
}
当我注释掉二元运算符时,程序按预期运行。我的问题是如何保护我的二元运算符免受空引用的影响,以便我可以保留它们以进行手动比较?感谢您的时间。