0

我已经实现了 iEquatable 接口:

LineItem : IEquatable<LineItem>

但现在我想Equals(...)通过单步调试代码来调试我的方法。但即使在调试模式下,单步执行也不会进入它(即 F11),并且在方法中放置断点也不会让我进入它。我该如何调试它?

并不是说它应该是相关的,但这是我的Equals方法:

public bool Equals(LineItem other)
            {
                List<bool> individuals = new List<bool>();

                individuals.Add(DateTime.Equals(Expiry, other.Expiry));
                individuals.Add(Code == other.Code);
                individuals.Add(Type == other.Type);
                individuals.Add(Class == other.Class);

                Func<object, object, bool> Compare = delegate(object A, object B)
                {
                    if (A == DBNull.Value || B == DBNull.Value)
                        return A == B;
                    else
                        return (double)A == (double)B;
                };

                individuals.Add(Compare(Strike, other.Strike));
                individuals.Add(Compare(Future, other.Future));
                individuals.Add(Compare(Premium, other.Premium));
                individuals.Add(Compare(Volatility, other.Volatility));
                individuals.Add(Compare(Volume, other.Volume));
                individuals.Add(Compare(OpenInterest, other.OpenInterest));
                individuals.Add(Compare(Delta, other.Delta));

                return !individuals.Contains(false);
            }

编辑: 我现在从我的代码中的其他地方调用该方法,如下所示:

if(!fo.Future.Equals(li))...

但这仍然不允许我调试它。

4

2 回答 2

15

您需要退后一步,首先学习如何正确实现相等方法。C# 被设计成一个“成功的坑”语言;也就是说,你应该自然而然地“陷入”以正确的方式做事。不幸的是,平等并不是 C# 中的“成功之坑”;语言设计者没能让第一次就做好。

这是我在覆盖平等时使用的模式。

首先,从编写一个能正确处理所有事情的私有静态方法开始。其他一切都将使用此方法。通过处理 (1) 引用相等性和 (2) 空检查来开始您的方法。

private static MyEquality(Foo x, Foo y)
{
  if (ReferenceEquals(x, y)) return true;
  // We now know that they are not BOTH null.  If one is null
  // and the other isn't then they are not equal.
  if (ReferenceEquals(x, null)) return false;
  if (ReferenceEquals(y, null)) return false;
  // Now we know that they are both non-null and not reference equal.
  ... check for value equality here ...
}

好的,现在我们有了它,我们可以用它来实现其他一切。

public override bool Equals(object y)
{
  return MyEquality(this, y as Foo);
}
public override int GetHashcode()
{
  // Implement GetHashcode to follow the Prime Directive Of GetHashcode:
  // Thou shalt implement GetHashcode such that if x.Equals(y) is true then 
  // x.GetHashcode() == y.GetHashcode() is always also true.
}
public bool Equals(Foo y)
{
  return MyEquality(this, y);
}

这是正确实施所必需IEquatable<T>.Equals的。您还应该考虑覆盖==运算符以保持一致:

public static bool operator ==(Foo x, Foo y)
{
    return MyEquality(x, y);
}
public static bool operator !=(Foo x, Foo y)
{
    return !MyEquality(x, y);
}

现在,无论您调用object.Equals(foo, bar)foo.Equals(bar)foo == bar,您的行为都是一致的。

于 2013-07-26T17:02:18.917 回答
4

LineItem.Equals(a, b)是一个静态方法调用Object.Equals(object, object);这不是你的方法。

a.Equals(object)如果您已覆盖此实现,但您没有覆盖它,此实现将调用。

于 2013-07-26T16:28:09.893 回答