This article mainly introduces the elaboration of C # with new and override to achieve the overriding difference of abstract class, small series think very good, and now share to everyone, but also for everyone to do a reference. Follow the small series together to see it.
One, the realization of abstraction
Using system;using system.collections.generic;using system.linq;using system.text;namespace Virtualdemo{ class Program { static void Main (string[] args) {//bclass A = new Bclass (); The abstract class cannot be instantiated Class1 C = new Class1 ();
bclass C2 = c; C2. MethodA (); C.methoda (); C2. MethodB (); C.methodb (); C2. METHODC (); C.METHODC (); Console.readkey (); } } Abstract class Bclass //Abstraction classes cannot be instantiated {public virtual void MethodA () {Console.WriteLine ("Bclassa");} public virtual void MethodB () {Console.WriteLine ("Bclassb");} public virtual void Methodc () {Console.WriteLine ("BCLASSC");} } Class Class1:bclass {public void MethodA () {Console.WriteLine ("MethodA");} If a virtual function does not pass the Override keyword in the subclass, then this method is not overridden, but is hidden public override void MethodB () {Console.WriteLine ("MethodB") ; } public override void Methodc () {base. METHODC (); } }}
The results obtained are as follows:
In summary: The virtual method of the abstract class needs to be rewritten, and there are two ways to rewrite the question, what is the difference between new and override?
Two, the difference between the new and override overrides:
Using system;using system.collections.generic;using system.linq;using system.text;namespace Virtualdemo{ class Program { static void Main (string[] args) { Teacher t = new Teacher (); Student stu = t; Stu. Exam (); Stu. Say (); T.say (); Console.readkey (); } } Public abstract class Student {public virtual void Exam () { Console.WriteLine ("Students have to take exams"); } Public void Say () { Console.WriteLine ("I am a Student");} } public class Teacher:student {public override void Exam () { Console.WriteLine ("Teacher does not have to test"); } //public override void Say ()//error, hint no virtual, cannot be rewritten //{ // Console.WriteLine ("I am a Teacher"); } public new void Say () { Console.WriteLine ("I am the Teacher") ; }}}
The results are shown as:
In summary:
1. If the base class does not have a virtual method defined, the subclass can only use new and cannot use the override
2, the base class has no virtual method defined, subclasses can use the new
3, subclasses use new is not called rewriting, but the subclass of a new method is created, but the newly created method is just the same name as the method in the base class
The above is a detailed description of C # with new and override to achieve the overriding difference of the abstract class content, more relevant content please pay attention to topic.alibabacloud.com (www.php.cn)!