Skip to main content
 首页 » 编程设计

c#之创建类型为 "derived class"的对象

2024年02月23日22freeliver54

我最近一直在研究类继承,并且不断遇到这段特定的代码。

public class Foo {       
 
 public bool DoSomething()  
 {  
   return false;  
 }  
}   
 
public class Bar : Foo {  
 
 public new bool DoSomething()  
 {  
   return true;  
 }  
}   
 
 public cass Test {  
 
  public static void Main () {    
 
    Foo test = new Bar ();  
 
    Console.WriteLine (test.DoSomething ());      
  }  
}  

这里让我感到困惑的是,如果是我,我会按 Bar 类型创建一个 Bar 实例......

Bar test = new Bar(); 

我不明白为什么它会按照代码中的方式创建。

请您参考如下方法:

编写这段代码可能是为了演示覆盖和隐藏基类方法之间的区别:

在这种情况下,使用 Foo 变量实例化一个 Bar 对象将使用基类方法 DoSomething() 并打印出 错误。如果 DoSomething 方法在基类中声明为虚拟方法并在派生类中被覆盖,则输出将为 true,如下例所示:

public class Foo {       
 
 public virtual bool DoSomething()  
 {  
   return false;  
 }  
}   
 
public class Bar : Foo {  
 
 public override bool DoSomething()  
 {  
   return true;  
 }  
}