为什么最后两行输出它们是什么?



谁能帮我理解一下

  1. 这个语句是否正确:BaseClass bcdc = new DerivedClass();意味着bcdc是BaseClass类的类型,它的值是派生类对象的类型?还有,这意味着什么?为什么一个对象会像那样被实例化,而不是像DerivedClass dc = new DerivedClass()中那样使类类型与被实例化的新对象相同?
  2. 为什么是bcdc.Method1() => Derived-Method1。是因为使用了关键字override,所以重写了虚拟的Method1吗?
  3. 为什么是bcdc.Method2() => Base-Method2。我很困惑,因为在派生类的新关键字应该隐藏Base-Method2?
class BaseClass  
{  
public virtual void Method1()  
{  
Console.WriteLine("Base - Method1");  
} 
public void Method2()  
{  
Console.WriteLine("Base - Method2");  
} 
}  

class DerivedClass : BaseClass  
{  
public override void Method1()  
{  
Console.WriteLine("Derived - Method1");  
}  
public new void Method2()  
{  
Console.WriteLine("Derived - Method2");  
}  
}
class Program  
{  
static void Main(string[] args)  
{  
BaseClass bc = new BaseClass();  //bc is of type BaseClass, and its value is of type BaseClass
DerivedClass dc = new DerivedClass();  //dc is of type DerivedClass, and its value is of type DerivedClass
BaseClass bcdc = new DerivedClass();  //bcdc is of type BaseClass, and its value is of type DerivedClass.

bc.Method1();  //Base - Method1 
bc.Method2();  //Base - Method2
dc.Method1();  //Derived - Method1
dc.Method2();  //Derived - Method2 
bcdc.Method1(); //Derived - Method1. ??
bcdc.Method2(); //Base - Method2.  ??
}   
} ```

这意味着bcdc类型为BaseClass类,其值类型为DerivedClass对象?

是的。然而,我更愿意将其称为DerivedClass对象BaseClass引用

同样,这意味着什么,为什么一个对象会像这样被实例化,而不是让类类型与被实例化的新对象相同,如在DerivedClass dc = new DerivedClass()中?

一种情况是当你想调用显式接口方法时。但是,如果您调用方法MyMethod(BaseClass bcdc).

,则会发生非常类似且更常见的情况:在这个简单的程序中,所有类型在编译时都很容易知道。但是对于更大的程序,情况就不是这样了,一个方法接受一个BaseClass参数,它可以有很多不同的实现,当代码编译时,所有的实现可能都不知道。

为什么bcd . method1 () =>Derived-Method1。是因为使用了关键字override,所以重写了虚拟的Method1吗?

是的,对于标记为虚的方法,编译器将插入一个检查,根据实际的对象类型,即DerivedClass,将方法调用转发给被覆盖的方法。这有时被称为虚拟调度动态调度。也就是说,方法将在运行时根据对象类型动态选择。.

为什么bcdc.Method2() =>Base-Method2。我很困惑,因为在派生类的新关键字应该隐藏Base-Method2?我以为这是新关键字的功能。

Method2不是虚拟的,所以不会有动态调度。所以引用类型,即BaseClass,将用于确定被调用的方法。这被称为静态调度,即被调用的方法可以在编译时静态确定。

最新更新