我还不熟悉运算符重载。我认为自己做得很好,直到遇到了这个问题。在!=运算符上抛出了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");
}
}
}
当我注释掉二元运算符时,程序按预期运行。我的问题是如何保护我的二元运算符不受空引用的影响,以便我可以将它们用于手动比较? 感谢您的时间。
!=
进行比较的其中一个Task
对象被设置为null
。 - Sergey Kalinichenkot1
和/或t2
可能为空。 - Mike Christensen