C # access permission reference
Different behaviors in the same code are created. The base class (Super) and the derived class (Sub) each class has a field and a public method getField, and is initialized as 1 in inline mode, the getField method returns the field. C # and Java code and running results: C # copy the code class Super {public int field = 0; public int getField () {return field ;}} class Sub: super {public int field = 1; public int getField () {return field ;}} class Program {private static void Main (string [] args) {Super sup = new Sub (); Console. writeLine ("sup. getField () result: "+ sup. getField (); Console. readKey () ;}} copy code Java copy code class Super {public int field = 0; Public int getField () {return field;} class Sub extends Super {public int field = 1; public int getField () {return field ;}} public class polymorphicDefects {public static void main (String [] args) {Super sup = new Sub (); System. out. println ("sup. getField () result: "+ sup. getField () ;}} the Java code execution result of the copied code shows polymorphism, while the C # method does not show polymorphism. More specifically, the object sub in C # does not call the method in its actual type Sub, but calls the method of the parent class. I may be confused when I use C # because I am not familiar with Java. In fact, the C # team has added the concept of referencing access permissions, A reference represents its access permission. A Sub reference can only access its own methods in the Sub type. Of course, the C # method does not support too many methods, but uses virtual methods to express method polymorphism. For example, copy the code class Super {public int field = 0; public virtual int getField () {return field;} class Sub: Super {public int field = 1; public override int getField () {return field ;}} class Program {private static void Main (string [] args) {Super sup = new Sub (); Console. writeLine ("sup. getField () result: "+ sup. getField (); Console. readKey () ;}} copy the code. My views on introducing the access permission for reference in C. The introduced C # With reference access permissions is more powerful than Java and a new feature than Java. Of course, there are two things, the introduction of that access permission makes C # more complex and difficult. I don't know what other children's shoes think. I can share more ideas in the comment area.