簡體   English   中英

等於對結構不起作用?

[英]Equals doesn't work on structs?

由於非常可怕的原因,我在雇主申請中有這個結構。

我試圖覆蓋相等運算符,但是我得到錯誤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));
    }
}

更新:似乎==不起作用,但Equals確實如此。

沒有必要在結構上實現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 == right);
}

強烈建議你避開那些公共領域。 除非你小心,否則可變結構會引起任何數量的意外副作用。

(您還應遵循.NET命名約定,如果使用對不同類型的實例的引用調用Equals(object)方法,則返回false ,而不是無條件轉換。)

覆蓋Equals方法也不會自動實現== 您仍然需要手動重載這些運算符並將它們提供給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);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM