[英]Casting Deriving Class as Base Class
假设我有这个:
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
如何转换为基类?
我知道new关键字将覆盖派生类中的方法实现,并且当派生类的实例变量用于调用重写的方法时将执行该关键字,但是我不知道它是什么类型的Conversion。似乎既不是隐式也不是显式,可能是类型转换,但是我对语法感到困惑。
任何解释表示赞赏。
我知道new关键字将覆盖派生类中的方法实现
不会 。它不会覆盖基类的方法。 它声明了一个新的独立方法,该方法的名称相同且具有相同的签名。 效果是它隐藏了在基类中声明的相同签名方法,从而有效地使在基类中声明的相同签名方法的调用复杂化。
在您的示例中,没有任何“类型转换”。 可以将类型转换视为提供实例的特定视图-将类合同的特定部分暴露给用户。 仅此而已。
例:
// 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();
实际上,没有转换。 您只能通过这种方式查看对象。
上例中的变量bc如何转换为基类?
当您将新的DerivedClass
实例分配给BaseClass
类型的变量时,将执行此隐式转换:
BaseClass bc = new DerivedClass();
啊,我刚刚找到了这个 ,我说那似乎不是一个隐式转换,这是我的错。
对于引用类型,从类到其直接或间接基类或接口中的任何一个始终存在隐式转换。 不需要特殊的语法,因为派生类始终包含基类的所有成员。
Derived d = new Derived(); Base b = d; // Always OK.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.