C#继承怀疑 [英] C# Inheritance Doubt

查看:99
本文介绍了C#继承怀疑的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


我有个疑问 .基类引用何时可以存储派生类对象,反之亦然.
像这样的输出是什么?为什么?

Hi,
I have a doubt . When can a base class reference store derived class object and vice versa.
Like what will be the output of this and why?

class A
    {
        public void x()
        {
            Console.WriteLine("hi");
        }
    }
    class B : A
    {
        public void y()
        {
            Console.WriteLine("hello");
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            A a = new B();
B b =new A();
b.x();
            a.y();
        }
    }

推荐答案

您的代码将无法编译.
Your code will not compile.
B b = new A();

是不允许的,因为B是从A派生出来的,而不是从A派生出来的.如果编译器允许这样做,
那么你可以说:

Is not allowed, because B is derived from A and not the other way around. If the compiler allowed this,
then you could say:

B b = new A();
b.y();

但是在运行时会发生什么?没有为类A的对象定义"y"方法,因此无法调用该方法.编译器通过拒绝让您进行会导致问题的设计时间分配来防止此运行时错误.

这有点像说福特是一辆汽车,所以每辆汽车都有一个福特徽章-这是胡说八道.

But what would happen at run time? The "y" method is not defined for objects of class A, so the method could not be called. The compiler prevents this run time error by refusing to let you make a design time assignment that would cause the problem.

It''s a bit like saying a Ford is a Car, so every Car has a Ford badge - which is nonsense.


为什么不在调试器下运行它并查看你自己?
Why don''t you run it under the debugger and see for yourself?


这篇关于C#继承怀疑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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