Methods for using base class protected members in C # derived classes

Source: Internet
Author: User

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.