Sono ancora nuovo per gli operatori che sovraccaricano. Ho pensato che stavo facendo un ottimo lavoro fino a quando non avrò colpito questo problema. NullReferenceException viene lanciata sull'operatore! =. Presumo che lo usi nel metodo CompareTo ma non ne sono del tutto sicuro. Se qualcuno può indicarmi la giusta direzione, sarei molto grato.Come sovrascrivere correttamente l'uguaglianza?
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");
}
}
}
Quando commento agli operatori binaory il programma funziona come previsto. La mia domanda è: come posso proteggere i miei operatori binari da riferimenti null, quindi posso tenerli per confronti manuali? Grazie per il tuo tempo.
Uno degli oggetti 'Task' che si sta confrontando con'! = 'È impostato su' null'. – dasblinkenlight
Destra-o .. È necessario assumere 't1' e/o' t2' può essere nullo in tutte quelle funzioni statiche. –