虚拟,覆盖和新关键字 [英] Virtual, Override and New Keyword

查看:95
本文介绍了虚拟,覆盖和新关键字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嗨朋友。,



我对以下程序感到困惑:



Hi Friends.,

I am confused with the below program:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Learn
{
    class Program
    {
        static void Main(string[] args)
        {
            // Reference B through A.
            A ab = new B();
            ab.Y();

            // Reference C through A.
            A ac = new C();
            ac.Y();

            Console.Read();
        }
    }

    class A
    {
        public virtual void Y()
        {
            // Used when C is referenced through A.
            Console.WriteLine("A.Y");
        }
    }

    class B : A
    {
        public override void Y()
        {
            // Used when B is referenced through A.
            Console.WriteLine("B.Y");
        }
    }

    class C : A
    {
        new public void Y()
        //public void Y() // Can be "new public void Y()"
        {
            // Not used when C is referenced through A.
            Console.WriteLine("C.Y");
        }
    }
}





BY

AY



我从 dotnetperls 获得此示例



根据他们的提示我明白我们可以使用 New Modifier <隐藏派生类中的基类功能/ a>关键字。



在上面的示例程序中,我有一个C类继承了A类。这里我使用new关键字来隐藏基类函数。但它仍然显示输出为AY而不是CY



如果任何人可以向我解释这个问题会很棒。



B.Y
A.Y

I got this example from dotnetperls

As per their tips I understood that we can Hide the function of base class in derived class using New Modifier keyword.

In the above sample program I have a class C which inherits class A. Here I am using new keyword to hide the base class function. But still it is displaying the output as A.Y instead of C.Y.

It would be great if any one can explain me about this.

推荐答案

因为你正在写作。



Its because you are writing.

A ac = new C();



而不是


instead of

C ac = new C();





变量ac被记为基类A,因为您将其引用为这样。



你也可以尝试将ac投射到C中,在你的ac.Y()后执行此操作;





variable ac is remembered as baseclass A since you reference it as such.

You can also try to cast ac into C, by doing this after your ac.Y();

((C)ac).Y();


这篇关于虚拟,覆盖和新关键字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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