等于对结构不起作用?

时间:2013-04-02 15:10:13

标签: c# .net

出于非常可怕的原因,我在雇主申请中有这个结构。

我试图覆盖相等运算符,但是我收到错误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

2 个答案:

答案 0 :(得分: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),而不是无条件地转换。)

答案 1 :(得分:3)

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