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