"Go" writing high-quality Code 157 recommendations for improving C # programs--Recommendation 99: Overriding should not use sub-class parameters

Source: Internet
Author: User

Recommendation 99: Overriding should not use child class parameters

When overridden, if a child class parameter is used, it may deviate from the designer's intended target. For example, there is an inheritance system as follows:

    class Employee    {    }    class  manager:employee    {    }

The Setsalary method in type Managersalary now overrides the same method in salary, and the overridden method takes a subclass parameter:

    class Salary    {        publicvoid  setsalary (Employee e)        {            Console.WriteLine (" The clerk was set up a salary. ");        }    }     class managersalary:salary    {        publicvoid  setsalary (Manager m)        {            Console.WriteLine ( " the manager was set up to pay. ");        }    }

The caller's code looks like this:

        Static void Main (string[] args)        {            new  managersalary ();            M.setsalary (new  Employee ());        }

The designer's intention was to set the manager's salary, but the actual code was to set the employee's salary.

The output is:

The clerk was set up a salary.

Therefore, when overriding, the use of sub-class parameters has some risk, should avoid this design. The correct approach should still use the employee type parameter, which at least allows the compiler to remind us to use the New keyword.

Turn from: 157 recommendations for writing high-quality code to improve C # programs Minjia

"Go" writing high-quality Code 157 recommendations for improving C # programs--Recommendation 99: Overriding should not use sub-class parameters

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.