[英]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'
. 我试图覆盖相等运算符,但是我得到错误
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. 更新:似乎
==
不起作用,但Equals
确实如此。
There is no need to implement Equals
on structs. 没有必要在结构上实现
Equals
。
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.) (您还应遵循.NET命名约定,如果使用对不同类型的实例的引用调用
Equals(object)
方法,则返回false
,而不是无条件转换。)
Overriding the Equals
method doesn't automatically implement ==
as well. 覆盖
Equals
方法也不会自动实现==
。 You still need to manually overload those operators and feed them to the Equals
method 您仍然需要手动重载这些运算符并将它们提供给
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.