简体   繁体   中英

Equals doesn't work on structs?

For extremely horrible reasons, I have this struct in my employers application.

I tried to override the equality operator, but I get error Error 9 Operator '==' cannot be applied to operands of type 'TR_St_DateTime' and 'TR_St_DateTime' .

What am I missing?

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: It seems that == doesn't work but Equals does.

There is no need to implement Equals on structs.

You haven't overloaded the == operator, which is why the compiler's complaining. You just need to write:

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);
}

I would strongly recommend that you avoid those public fields though. Mutable structs can cause any number of unintended side-effects unless you're careful.

(You should also follow .NET naming conventions, and return false if the Equals(object) method is called with a reference to an instance of a different type, rather than unconditionally casting.)

Overriding the Equals method doesn't automatically implement == as well. You still need to manually overload those operators and feed them to the Equals method

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM