调用父类被覆盖的虚方法 [英] Calling overriden virtual methods from the parent class

查看:237
本文介绍了调用父类被覆盖的虚方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设你正在写原来的C#对象类和你想要的以下功能:

Say you were writing the original C# Object class and you wanted the following functionality:


  1. object1 == Object2的将比较引用,除非这个操作符重载

  2. object1!= Object2的总是返回对象的实际 object1 == Object2的

  1. object1 == object2 will compare references unless this operator is overridden
  2. object1 != object2 will always return the inverse of the object's ACTUAL object1 == object2

因此,举例来说,如果我有一个兔兔类(从派生的对象),使用耳朵的长度为equals方法,那么notequals方法(从 Object继承)应该返回true,如果兔子有不同的耳朵长度。

So, for example, if I have a Bunny class (derived from Object) which uses ear lengths as its equals method, then the notequals method (inherited from Object) should return true if the bunnies have different ear lengths.

这是我看到的问题是,如果我写我的对象类是这样的:

The problem that I see is that if I write my Object class something like:

public partial class Object {
    public virtual bool Equals(Object o2) {
       return (this === o2);
    }

    public bool NotEquals(Object o2) {
       return !this.Equals(o2);
    }
}



那么看起来就好像该定义将绑定NotEquals到对象的平等相待,而不是实际的派生类的equals。

then it seems like that definition will bind NotEquals to Object's Equals, not the actual derived class's equals.

有一些办法,这可以在不修改C#工作本身以任何方式?我不在乎这么多,它在C#中可能的,但我不在乎,如果有一些OOP原则,告诉我,我不应该期待这种合作的事情。

Is there some way that this can work without modifying C# itself in any way? I don't care so much that it's possible in C# but I care if there's some OOP principle which tells me that I shouldn't expect this sort of thing to work.

另外,我不知道这是否是对问题的根本,但这个想法是NotEquals是虚拟的,以及因此,它也可以由希望自己的 01派生类中重写! = O2 来从不同!(O1 O2 ==)。这个问题是由最近这次讨论。

Also, I'm not sure whether or not this is fundamental to the question, but the idea is for NotEquals to be virtual as well so that it too can be overridden by derived classes which want their o1 != o2 to be different from !(o1 == o2). This question is inspired by this recent discussion.

推荐答案

您所提供的代码的将会的调用派生等于方法。 等于是虚拟的,这意味着,当它被称为,最派生出来的的实施将会被使用。

The code you've provided will call the derived Equals method. Equals is virtual, and that means that when it is called, the "most derived" implementation will be used.

这篇关于调用父类被覆盖的虚方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆