简体   繁体   English

如何访问基类的部分成员

[英]How to access part of the members of base class

I have a base class 我有一个基类

class Administrator()
    {
         void addEmployee(){ some code };
         void Salary_PaySlip() { some code }; 
    }
class HR: Administrator
    {
            // make use of addEmployee()
    }
class Accountant: Administrator
    {
            // make use of void Salary_PaySlip()
    }

This is just an example. 这只是一个例子。

Here I want Accountant use the method Salary_PaySlip() only. 在这里,我希望Accountant使用Salary_PaySlip()方法。 The method addEmployee() should not be accessible by Accountant . Accountant不应该访问方法addEmployee() Same way class HR should only have access to the addEmployee() method. 同样, class HR应该只能访问addEmployee()方法。

Can Someone help me to solve this? 有人可以帮我解决这个问题吗?

Thanks in Advance 提前致谢

Your problem can be sumarized as the Single Responsibility Principle which is quite related to the Interface Segregation Principle (I suggest you check the SOLID principles of object oriented design : https://en.wikipedia.org/wiki/SOLID_(object-oriented_design) ) 您的问题可以归结为单一责任原则,它与接口隔离原则密切相关(我建议您检查面向对象设计的SOLID原则: https ://en.wikipedia.org/wiki/SOLID_(object-oriented_design

You created a class administrator which can add employees and PaySlip at the same time. 您创建了一个类管理员,可以同时添加员工和PaySlip。 However you want to segregate who is authorized to use some part of your class. 但是,您想要分离谁有权使用您班级的某些部分。 This is the sign that this class should be split in two different classes. 这是该类应分为两个不同类的标志。 One for each method. 每个方法一个。

You will then be able to create your "client" classes (those who use the methods). 然后,您就可以创建“客户端”类(使用这些方法的人)。 I suggest that you use composition rather than inheritance to get access to your administrator parts in the end as it's not sure it makes sense to have this inheritance link. 我建议你最后使用组合而不是继承来访问你的管理员部分,因为它不确定有这个继承链接是否有意义。

Sample code which is of course not relevant yet (but can't do better without more info) 示例代码当然不相关(但如果没有更多信息则无法做得更好)

public class EmployeeAdministrator()
{
    public void addEmployee(){ some code };
}

public class SalaryAdministrator()
{
    public void Salary_PaySlip() { some code };
}

public class HR 
{
    public EmployeeAdministrator Administrator { get; }
    // make use of addEmployee()
}

class Accountant
{
    public SalaryAdministrator Administrator { get; }
    // make use of void Salary_PaySlip()
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM