Skip to main content
 首页 » 编程设计

c#之将派生类转换为基类

2024年02月05日13yxwkf

假设我有这个:

using System; 
 
public class Program 
{ 
    public static void Main() 
    { 
        BaseClass bc = new DerivedClass(); 
        bc.Method1(); 
        bc.Method2(); 
        Console.WriteLine(bc.GetType().FullName); 
 
        // Output 
        // Derived - Method1 (override) 
       // Base - Method2 
       // DerivedClass 
    } 
} 
 
public class BaseClass 
{ 
    public virtual void Method1() 
    { 
        Console.WriteLine("Base - Method1"); 
    } 
 
    public virtual void Method2() 
    { 
        Console.WriteLine("Base - Method2"); 
    } 
} 
 
public class DerivedClass : BaseClass 
{ 
    public override void Method1() 
    { 
        Console.WriteLine("Derived - Method1 (override)"); 
    } 
 
    public new void Method2() 
    { 
        Console.WriteLine("Derived - Method2 (new)"); 
    } 
} 
 

如果派生类的实例变量被强制转换到基类,并且该实例变量用于调用被覆盖的方法,则该方法被override关键字覆盖将在派生类中执行实现,而用 new 关键字重写的将在基类中执行实现。

上面例子中的变量bc是如何转换为Base Class的?

我知道 new 关键字会覆盖派生类中的方法实现,当派生类的实例变量用于调用被覆盖的方法时,它会被执行,但我不知道不知道它是什么类型的转换.. 似乎不是隐式的也不是显式的,可能是类型转换,但我对语法感到困惑。

感谢任何解释。

请您参考如下方法:

I know that the new keyword will override the method implementation in the deriving class

没有。它不会覆盖基类的方法。它声明了一个新、独立的方法,只是名称相同并且具有相同的签名。结果是它隐藏在基类中声明的相同签名方法,有效地使调用在基类中声明的相同签名方法复杂化。

在您的示例中,没有任何“类型转换”。将类型转换 视为提供实例的特定 View ——向用户公开类契约的特定部分。仅此而已。

例子:

// instance of DerivedClass exposing its full contract via the 'dc' variable 
DerivedClass dc = new DerivedClass(); 
 
// the same instance of DerivedClass exposing its contract limited to what's declared in BaseClass 
BaseClass bc = dc; 
 
// calling Method2 as newly declared in DerivedClass 
dc.Method2(); 
 
// calling Method2 as declared in BaseClass—the following two lines are equivalent 
bc.Method2(); 
((BaseClass)dc).Method2();