11-12(11-12)

重写、重载重载:一个类中的方法与另一个方法同名,但是参数表不同,这种方法称之为重载方法。

重写:

重写(override)

复制代码public class C1{ public virtual string GetName() { return “叔祥”; }}

public class C2 : C1{ public override string GetName() { return “xiangshu”; }}

C1 c1 = new C1(); Console.WriteLine(c1.GetName());//输出“祥叔”

C2 c2 = new C2(); Console.WriteLine(c2.GetName());//输出“xiangshu”

//重点看这里

C1 c3 = new C2(); Console.WriteLine(c3.GetName());//输出“xiangshu” 复制代码覆盖(new)

复制代码public class C1{ public string GetName() { return “祥叔”; }}

public class C2 : C1{ public new string GetName() { return “xiangshu”; }}

C1 c1 = new C1();Console.WriteLine(c1.GetName());//输出“祥叔”

C2 c2 = new C2();Console.WriteLine(c2.GetName());//输出“xiangshu”

//重点看这里,和上面的重写作比较

C1 c3 = new C2();Console.WriteLine(c3.GetName());//输出“祥叔” 复制代码总结

1:不管是重写还是覆盖都不会影响父类自身的功能(废话,肯定的嘛,除非代码被改)。

2:当用子类创建父类的时候,如 C1 c3 = new C2(),重写会改变父类的功能,即调用子类的功能;而覆盖不会,仍然调用父类功能。

3:虚方法、实方法都可以被覆盖(new),抽象方法,接口 不可以。

4:抽象方法,接口,标记为virtual的方法可以被重写(override),实方法不可以。

5:重写使用的频率比较高,实现多态;覆盖用的频率比较低,用于对以前无法修改的类进行继承的时候。

————————

Override, overload: a method in a class has the same name as another method, but the parameter table is different. This method is called an overload method.

rewrite:

Override

复制代码public class C1{ public virtual string GetName() { return “叔祥”; }}

public class C2 : C1{ public override string GetName() { return “xiangshu”; }}

C1 c1 = new C1(); Console.WriteLine(c1.GetName());// Output “Uncle Xiang”

C2 c2 = new C2(); Console.WriteLine(c2.GetName());//输出“xiangshu”

//Focus here

C1 c3 = new C2(); Console.WriteLine(c3.GetName());// Output “Xiangshu” copy code overwrite (New)

复制代码public class C1{ public string GetName() { return “祥叔”; }}

public class C2 : C1{ public new string GetName() { return “xiangshu”; }}

C1 c1 = new C1(); Console.WriteLine(c1.GetName());// Output “Uncle Xiang”

C2 c2 = new C2();Console.WriteLine(c2.GetName());//输出“xiangshu”

//Focus here and compare it with the above heavy writing

C1 c3 = new C2(); Console.WriteLine(c3.GetName());// Output “Xiangshu” copy code summary

1: Neither rewriting nor overwriting will affect the function of the parent class itself (nonsense, for sure, unless the code is changed).

2: When creating a parent class with a subclass, such as C1 C3 = new C2 (), rewriting will change the function of the parent class, that is, calling the function of the subclass; Instead of overriding, the parent function is still called.

3: Virtual methods and real methods can be overwritten (New), but abstract methods and interfaces cannot.

4: Abstract methods, interfaces, and methods marked virtual can be overridden, but real methods cannot.

5: The frequency of rewriting is relatively high to realize polymorphism; The frequency of coverage is relatively low. It is used to inherit classes that cannot be modified before.