我最近问过这个问题:When would == be overridden in a different way to .equals?。我被引用到这篇文章:https://ericlippert.com/2013/10/07/math-from-scratch-part-six-comparisons/
我不完全理解对静态方法调用(==
和!=
)和动态方法调用(.Equals()
)的引用。请参阅以下代码:
public class A
{
private string Field1;
private string Field2;
public A(string field1, string field2)
{
Field1 = field1;
Field2 = field2;
}
public static bool operator ==(A a1, A a2)
{
throw new NotImplementedException();
}
public static bool operator !=(A a1, A a2b)
{
throw new NotImplementedException();
}
public override int GetHashCode()
{
throw new NotImplementedException();
}
public override bool Equals(object obj)
{
throw new NotImplementedException();
}
}
public class B : A
{
private string Field3;
private string Field4;
public B(string field1, string field2, string field3, string field4)
: base(field1, field2)
{
Field3 = field3;
Field4 = field4;
}
public static bool operator ==(B a1, B a2)
{
throw new NotImplementedException();
}
public static bool operator !=(B a1, B a2b)
{
throw new NotImplementedException();
}
public override int GetHashCode()
{
throw new NotImplementedException();
}
public override bool Equals(object obj)
{
throw new NotImplementedException();
}
}
以及下面的测试:
A a1 = new B("hello","hello","hello","hello");
A a2 = new B("hello", "hello", "hello", "hello");
var test1 = a1.Equals(a2);
var test2 = a1 == a2;
我不明白它以这种方式实现的原因?我今天晚上花了最后一小时用Google搜索,但是我仍然不清楚这个问题的原因。为什么动态调度.Equals()
并静态调度==
?
答案 0 :(得分:7)
df %>% mutate(newCol = replace(newCol, `last name` %in% c("a", "c", "e"), "No"))
是一个虚拟实例方法,受普通覆盖规则/多态性的约束。
.Equals()
是静态==
方法的语法糖,这是一个带有两个参数的普通静态方法调用,因此根本不进行动态调度。