C#,继承和转换.. !! [英] C#, Inheritance and casting..!!

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

问题描述

using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication1
{
    class A
    {
    }
    class B:A
    {
    }
    class c
    {
        static void Main(string[] args)
        {
            B obj1 = new A();
        }
    }
}



它会执行?? ..如果没有,..任何人都可以给我确切的答案吗?



Will it execute ??..and if not.. can anyone give me the exact answer ???

推荐答案

如果B是A的子类,那么我认为

obj1 = new B()很好,反之亦然


您可以使用超类来引用子类,但不能使用子类来引用超类


您也许可以进行强制转换
If B is a subclass of A then I think

A obj1 = new B() is fine but not vice versa


you can use a superclass to ref a subclass but not a subclass to ref a superclass


you might be able to cast it though


不,它不会执行.

如果编写A obj1 = new B();,它将执行.

为什么?

因为A 是基类,而B 是扩展B的类.因此,根据OOP,B 是一个A,因为A 在继承层次结构中位于较高位置.因此,始终可以将B 的对象分配给A的引用.但是,相反的情况不会执行.

但是,如果按以下方式强制转换对象,则它将编译,但是不会执行:

No, it won''t execute.

If you write A obj1 = new B();, it will execute.

Why?

Because, A is the base class and B is the class that extends B. So, according to OOP, B "is a" A as A is in upper position in the inheritance hirarchy. So, it is always possible to assign an object of B to a reference of A. But, the opposite wouln''t execute.

However, If you cast the object as follows, then it will compile, but, won''t execute:

B obj1 = (B)new A();


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

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