static void Main() { MyDerivedClass derived = new MyDerivedClass(); MyBaseClass mybc = (MyBaseClass)derived; derived.Print(); mybc.Print(); }
static void Main() // Main { SecondDerived derived = new SecondDerived(); // Use SecondDerived. MyBaseClass mybc = (MyBaseClass)derived; // Use MyBaseClass. derived.Print(); mybc.Print(); }
static void Main() { MyDerivedClass derived = new MyDerivedClass(); MyBaseClass mybc = (MyBaseClass)derived; derived.Print(); // Call Print from derived portion. mybc.Print(); // Call Print from base portion. }
static void Main() { MyDerivedClass derived = new MyDerivedClass(); MyBaseClass mybc = (MyBaseClass)derived; derived.Print(); // Call Print from derived portion. mybc.Print(); // Call Print from base portion. // mybc.var1 = 5; // Error: base class reference cannot // access derived class members. }
public void _01() { var derived = new MyDerivedClass(); derived.Print(); // 父类变量指向子类对象, 通过父类变量只能访问父类成员 MyBaseClass mybc = derived; mybc.Print(); }
public void _01() { var derived = new MyDerivedClass(); derived.Print(); // 父类变量指向子类对象, 通过父类变量只能访问父类成员, // 但是如果这个成员在父类是标记为 virtual, 在子类是标记为 override, 则此时访问的是子类成员. MyBaseClass mybc = derived; mybc.Print(); }