简体   繁体   English

派生给基类变量的派生类对象

[英]Derived class object assigned to Base class variable

Below code, A is base class and B is a derived class. 在代码下面,A是基类,而B是派生类。 When I do A a1 = new B(); 当我做A a1 = new B(); and call what a1 can see, I see that it can only see class A field because a1 is of A type so it can not see B specific members and this is what I expected too. 并调用a1可以看到的内容,我看到它只能看到A类字段,因为a1是A类型的,因此它看不到B特定成员,这也是我所期望的。 But when I call a1.Display() it prints out B's display method. 但是,当我调用a1.Display()时,它将打印出B的显示方法。 How come a1 can not see B field but can reach B's display method? a1为什么看不到B字段却能到达B的显示方式?

using System;    

namespace Test
{
class A
{
    public int varOfClassA = 5;

    public virtual void Display()
    {
        Console.WriteLine("I am Class A");
    }
}

class B : A
{
    public int varOfClassB = 10;

    public override void Display()
    {
        Console.WriteLine("I am class B");
    }
}

class Program
{
    static void Main(string[] args)
    {
        A a1 = new B();
        Console.WriteLine(a1.varOfClassA);  //prints out "5"
        a1.Display();   //prints out "I am class B" why???
    }
}
}

That's because the method Display() is declared in B as overrides . 这是因为方法Display()B被声明为overrides
Every member that overrides a base class member will be executed whether the reference type is of the derived or of the base class. 无论引用类型是派生类还是基类,都将执行覆盖基类成员的每个成员。

When you do A a1 = new B(); 当你做A a1 = new B(); what you have is an instance of B , not an instance of A . 您拥有的是B的实例,而不是A的实例。
However, since the reference is of type A , you can only access whatever methods of B that also exists in A , either inherited as is or overridden. 然而,由于基准的类型是A ,则只能访问任何方法B也存在于A ,无论是遗传原样或覆盖。

As a rule, in such cases, when your code executes a method on a1 , the method that gets executed is the B method, since that's the type of instance you have. 通常,在这种情况下,当您的代码在a1上执行一个方法时,执行的方法是B方法,因为这是您拥有的实例的类型。 However, this rule does have an exception - and that is when instead of override , the method in B is declared as new . 但是,此规则确实有一个例外-即,当B的方法而不是override被声明为new In such cases, the method (or property) of A is executed, even though your instance is of type B : 在这种情况下,即使实例的类型为B ,也会执行A的方法(或属性):

class A
{
    public virtual void Display()
    {
        Console.WriteLine("I am Class A");
    }

    public int MyIntValue { get{ return 5; } }
}

class B : A
{
    public override void Display()
    {
        Console.WriteLine("I am class B");
    }

    public new int MyIntValue { get{ return 5; } }
}

Using the above classes: 使用以上类:

A a1 = new B();

a1.Display(); // Displays "I am class B"
Console.WriteLine(a1.MyIntValue.ToString()); // Displays "5"

You can see a live demo on rextester. 您可以在rextester上观看现场演示。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM