We know that in C #, inheritance allows a base class with common data and methods to be widely used to reduce the amount of code, so that derived classes have all members of the base class (except constructors, etc.), and we can naturally use the members of the base class through derived class instances. So how do we use base class members in derived classes when the base class members are protected decorated, and the usage methods are described below.
First we put in a wrong code of use:
1 class Program2 {3 Static voidMain (string[] args)4 {5 console.readline ();6 7 }8 }9 Public class PersonTen { One protected stringName A { - Set{name =value;} - Get{returnname;} the } - Private stringname; - } - Public classStudent:person + { - Public voidMethod ( person person) + { APerson. Name="Rurui"; at } -}
In a derived class, we cannot refer to an instance of a base class to act on a base class member, and we should use an instance of the derived class, as in the following code:
1 class Program2 {3 Static voidMain (string[] args)4 {5 console.readline ();6 }7 8 Public class Person9 {Ten protected stringName One { A Set{name =value;} - Get{returnname;} - } the Private stringname; - } - Public classStudent:person - { + Public voidMethod ( person person) - { +Student stu = person asStudent; AStu. Name ="Rurui"; at } - - } -}
Methods for using base class protected members in C # derived classes