Question about how to shield the methods and attributes of the base class
Many book or Online writers describe this issue in this way, and use private new to block it. I believe that anyone who can write those articles must be a master. I have never done any experiments in this field. Today, a colleague suddenly asked me this question. I answered him in this way, but his piece of code completely damaged my perfect image in his mind. I am very ashamed of this. Let's take a look at this Code:
Using System;
Using System. Collections. Generic;
Using System. Text;
Namespace ConsoleApplication3
{
Class
{
Public void Foo ()
{
Console. WriteLine ("AAAAAAAAA ");
}
}
Class B:
{
Private new void Foo ()
{
Console. WriteLine ("bbbbbbbbbbbb ");
}
}
Class Program
{
Static void Main (string [] args)
{
B B = new B ();
B. Foo ();
Console. ReadLine ();
}
}
}
Run it by yourself, so I will not post the running result.
Do not block the methods and attributes of the base class in C. If Class B inherits from Class A, Class B must inherit all behaviors and attributes of Class A. Otherwise, Class B cannot constitute A strict inheritance relationship. For example, if cats have eyes, tigers and cats should both have eyes (except for natural disability). If tigers do not have eyes, Tigers should not be classified as cats. If you have to block a certain attribute and method, I suggest you do not inherit from that class, which will lead to chaotic relationships. Of course, this is an ideal situation.
The method or attribute call of C # is searched from the hierarchy of the inheritance relationship to the high-level one. The method Foo is not found in the common methods of Class B, if this method is found on the internet and found in Class A, it will call the Foo method of Class A. If the method is still not found in Class A, it will continue to look up, until the object class is found.
The analysis is superficial. Sorry.