對於非常可怕的原因,我在我的僱主應用程序中有這個結構。Equals不適用於結構?
我試圖覆蓋相等運算符,但我得到錯誤Error 9 Operator '==' cannot be applied to operands of type 'TR_St_DateTime' and 'TR_St_DateTime'
。
我錯過了什麼?
public struct TR_St_DateTime : IEquatable<TR_St_DateTime>
{
public int Year;
public int Month;
public int Day;
public int Hour;
public int Minute;
public int Second;
public TR_St_DateTime(DateTime time)
{
Day = time.Day;
Hour = time.Hour;
Minute = time.Minute;
Second = time.Second;
Month = time.Month;
Year = time.Year;
}
public override bool Equals(object obj)
{
TR_St_DateTime o = (TR_St_DateTime) obj;
return Equals(o);
}
public override int GetHashCode()
{
return Year^Month^Day^Hour^Minute^Second;
}
public override string ToString()
{
return String.Format("{0}/{1}/{2}", Day, Month, Year);
}
public bool Equals(TR_St_DateTime other)
{
return ((Day == other.Day) && (Month == other.Month) && (Year == other.Year) && (Minute == other.Minute) && (Hour == other.Hour) && (Second == other.Second));
}
}
UPDATE: 看來==
不工作,但Equals
一樣。
對結構沒有必要實現Equals
。
確切的錯誤是什麼? –
錯誤運算符'=='不能應用於類型'TR_St_DateTime'和'TR_St_DateTime'的操作數 – Nahum
運算符==與方法Equals不相同,而且的確經常給出不同的結果。 – harold