继承与方法重写
public class A { public virtual void Fun1(int i) { Console.WriteLine(i); } public void Fun2(A a1) { a1.Fun1(1); Fun1(5); } } public class B : A { public override void Fun1(int i) { base.Fun1(i + 1); } } class Program { public static void Main() { B b = new B(); A a = new A(); a.Fun2(b); b.Fun2(a); Console.ReadKey(); } }
输出结果是
A a = new A();
B b = new B();
a.Fun2(b); 将子类B的实例b作为参数传递给父类A的引用a1。Fun2的this是父类的实例a
a1.Fun1(1); 输出2 因为父类的变量a1里实际存储的是子类的实例b,所以这里调用的是子类Fun1
Fun1(5); 输出5 这里的调用,是this.Fun1(5)。而这里的this是a,所以调用的是父类的Fun1
b.Fun2(a); 将父类A的实例作为参数传递,Fun2的this是b
a1.Fun1(1); 输出1 因为父类的变量a1里实际存储的是父类的实例a,所以这里调用的是父类的Fun1
Fun1(5) 输出6 这里的调用是this.Fun1(5);而这里的this是b,所以这里调用的是子类的Fun1
需要留意的是类A中的Fun2方法,在里面调用Fun1的时候,相当于是this.Fun1
ps:如果把B中的override改为new的话,输出的结果:
1
5
1
5
For example - I have a base class Fruit with a function Details(). There is another class Mango which inherits Fruit but also has a function named Details().
public class Fruit { public void Details() { } } public class Mango : Fruit { public void Details() { } }
As per the overriding principle, an object of Fruit can call Details() of Fruit, if it stores the instance of Fruit.
The object of Fruit can call the method- Details of class Mango, if it stores the instance of class Mango.
Fruit a = new Fruit(); a.Details(); // Calls the method- Details of base class Fruit a = new Mango(); a.Details(); // Calls the method- Details of derived class Mango
Ok, so we learned what is overriding.