繁体   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