覆盖和隐藏之间的确切区别 [英] Exact difference between overriding and hiding

查看:111
本文介绍了覆盖和隐藏之间的确切区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

任何人都可以用内存和引用来说明重写和隐藏的工作.

Can anybody tell the working of overriding and hiding in terms of memory and references.

class A
{
    public virtual void Test1() { //Impl 1}
    public virtual void Test2() { //Impl 2}
}
class B  : A
{
    public override void Test1() { //Impl 3}
    public new void Test2() { Impl 4}
}

static Main()
{
    A aa=new B() //This will give memory to B
    aa.Test1(); //What happens in terms of memory when this executes
    aa.Test2(); //-----------------------SAME------------------------
}

这里的内存属于类B,但是在第二条语句 aa.Test2 中,将调用类A的方法.为什么?如果B有内存,那么应该调用B的方法(以我的观点).

Here memory is with class B but in the second statement aa.Test2 class A's method will be called. Why is it? If B has memory then B's method should be called (in my point of view).

任何非常深入,完整地描述此基础知识的链接/练习都会有很大帮助.

Any link / exercise that describes this fundamental very deeply and completely will be a big help.

推荐答案

看看为了解释(在我的理解范围内),这些方法都放在插槽"中. A有两个插槽:一个用于Test1,一个用于Test2.

To paraphrase (to the limits of my comprehension), these methods go into "slots". A has two slots: one for Test1 and one for Test2.

由于A.Test1被标记为virtual,并且B.Test1被标记为override,所以Test1B实现不会创建自己的插槽,而是会覆盖A的实现.无论您将B的实例视为B还是将其强制转换为A,该插槽中都具有相同的实现,因此您始终会得到B.Test1的结果.

Since A.Test1 is marked as virtual and B.Test1 is marked as override, B's implementation of Test1 does not create its own slot but overwrites A's implementation. Whether you treat an instance of B as a B or cast it to an A, the same implementation is in that slot, so you always get the result of B.Test1.

相比之下,由于B.Test2被标记为new,因此它将创建自己的 new 插槽. (就像它没有被标记为new而是被赋予一个不同的名称一样.)ATest2实施仍然在其自己的插槽中存在".它被隐藏而不是被覆盖.如果将B的实例视为B,则会得到B.Test2;如果将其强制转换为A,则无法查看新插槽,并且A.Test2被调用.

By contrast, since B.Test2 is marked new, it creates its own new slot. (As it would if it wasn't marked new but was given a different name.) A's implementation of Test2 is still "there" in its own slot; it's been hidden rather than overwritten. If you treat an instance of B as a B, you get B.Test2; if you cast it to an A, you can't see the new slot, and A.Test2 gets called.

这篇关于覆盖和隐藏之间的确切区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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