如何调用 == 运算符来调用子级的实现?
我有
public abstract class DataClass
{
public static bool operator ==(DataClass left, DataClass right)
{
return left.Equals(right);
}
}
,这就是发生的情况
object left = new DataClass();
object right = new DataClass();
bool expected = true;
bool actual;
actual = ((DataClass)left) == ((DataClass)right);
Assert.AreEqual(expected, actual); // passes
actual = left == right;
Assert.AreEqual(expected, actual); // fails
如何让它调用正确的实现,而不需要显式地转换它?
I have
public abstract class DataClass
{
public static bool operator ==(DataClass left, DataClass right)
{
return left.Equals(right);
}
}
and this is what happens
object left = new DataClass();
object right = new DataClass();
bool expected = true;
bool actual;
actual = ((DataClass)left) == ((DataClass)right);
Assert.AreEqual(expected, actual); // passes
actual = left == right;
Assert.AreEqual(expected, actual); // fails
How to make it call the right implementation, without casting it explicitly?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
静态
方法不受多态行为的影响(即它们不能被覆盖)。需要演员阵容。有关可能的解决方法,请参阅此相关问题:覆盖静态方法
很可能您将不得不求助创建实例方法或重写
Equals
。static
methods are not subject to polymorphic behavior (i.e. they cannot be overriden). The cast is required.For a possible workaround see this related question: Override a static method
Most likely you will have to resort to creating an instance method or overriding
Equals
instead.您不能这样做,因为运算符是静态的,并且根据定义它们不能是虚拟的/重写的。
如果我遇到同样的问题,我最终会重写 bool Equals(object o) 并使用该方法而不是运算符。如果这不是一个选择,那么演员阵容是必要的。
You can't do that as operators are static and by definition they can not be virtual / overriden.
In cases where I've had the same issue I ended up overriding
bool Equals(object o)
and using the method instead of the operator. If that is not an option then the cast is necessary.