2013-04-02 46 views
2

對於非常可怕的原因,我在我的僱主應用程序中有這個結構。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

+1

確切的錯誤是什麼? –

+0

錯誤運算符'=='不能應用於類型'TR_St_DateTime'和'TR_St_DateTime'的操作數 – Nahum

+0

運算符==與方法Equals不相同,而且的確經常給出不同的結果。 – harold

回答

10

您沒有重載==運算符,這就是編譯器抱怨的原因。你只需要編寫:

public static bool operator ==(TR_St_DateTime left, TR_St_DateTime right) 
{ 
    return left.Equals(right); 
} 

public static bool operator !=(TR_St_DateTime left, TR_St_DateTime right) 
{ 
    return !(left == right); 
} 

我會強烈建議您避免這些公共領域雖然。除非您小心,否則可變結構可能會導致任何數量的意外副作用。

(您也應該遵循.NET命名約定,並返回false如果Equals(object)方法被調用,以不同類型的實例的引用,而不是無條件地鑄造。)

+0

約翰,你是一個主人。 – Nahum

+0

@NahumLitvin - 除了「主人」瘋了,約翰不瘋狂。 **是的,我做了一個'神祕博士'參考** –

+0

我每次讀到你的答案時都會學到一些東西。十多年來,我一直在做一些東西,如實現相等接口或重寫'Equals' - 但我相信我現在將構建自己的'=='和'!='運算符! **一個問題,**是否比說平等接口等更高效呢? –

3

重寫Equals方法沒有按」 t也會自動執行==。您仍然需要手動超載這些操作員並將它們送入Equals方法

public static bool operator==(TR_St_DateTime left, TR_St_DateTime right) { 
    return left.Equals(right); 
} 

public static bool operator!=(TR_St_DateTime left, TR_St_DateTime right) { 
    return !left.Equals(right); 
} 
+0

john毆打你幾秒鐘:) – Nahum

+1

@NahumLitvin如果你看看時間戳,我揍他:) – JaredPar

相關問題