【问题标题】:How to hide one property from one of the derived class?如何从派生类之一隐藏一个属性?
【发布时间】:2016-07-03 08:03:19
【问题描述】:

我有一个场景,我的基类 (Employee) 包含很少的属性,并且它有两个子类(PermanentEmployeeContractEmployee)。现在有一个属性,它只是 PermanentEmployee (MedicalCoverage) 的一部分。而且我正在使用多态性在运行时决定员工的类型,因此我需要将 MedicalCoverage 属性作为基类的一部分,以便我可以在访问员工对象的客户端代码中访问它。我不希望 ContractEmployee 拥有这个属性那么如何才能实现这个或这个设计的任何替代方案。 基类员工长这样

     Public Class Employee
        Public EmployeeId As Integer
        Public EmployeeFirstName As String
        Public EmployeeLastName As String
        Public Salary As Integer
        Public Overridable ReadOnly Property bonus As Double
          Get
             Return Salary
          End Get
       End Property
    End Class

我想让 MedicalCoverage 成为 PermanentEmployee 的一部分

Public Class PermanantEmployee
    Inherits Employee

    Public Overrides ReadOnly Property bonus As Double
        Get
            Return 15 * Salary
        End Get
    End Property
   Public Property MedicalCoverage As Double 'The property to be accessed only here
End Class

合同雇员是这样的

    Public Class ContractEmployee : Inherits Employee

        Public Overrides ReadOnly Property bonus As Double
            Get
                Return 12 * Salary
            End Get    
        End Property
       'The MedicalCoverage property is not part of the class here
    End Class

【问题讨论】:

    标签: .net vb.net oop polymorphism


    【解决方案1】:

    简短的回答。你不能。这是继承的本质。 如果某物是 Employee 并且该员工具有属性 MedicalCoverage 则任何从 Employee 继承的类都将具有此属性。
    但只是一个快速的心理游戏。如果您将 ContractEmployee 存储在类型为 Employee 的变量中并尝试访问 MedicalCoverage 属性,程序应该怎么做?
    如果您坚持这个想法,那么您可以将 Employee 中的属性定义为虚拟的,并在 ContractEmployee 中覆盖它,并抛出此实例不支持此属性的异常。
    如果您创建一个接口,您仍然无法通过 Employee 类型变量访问该属性,并且仍然必须转换为接口类型,因此您只需将该属性添加到 PermanantEmployee 中,如果实例是 PermanentEmployee 您可以转换为它以访问属性。

    【讨论】:

    • 非常有帮助。谢谢@Péter
    【解决方案2】:

    这个问题更多地基于意见。但如果我要实现这一点,我将使用“is”运算符来决定是否调用该属性。

    if emp is PermanantEmployee then
         (emp as PermananantEmployee).MedicalCoverage = 12.00
    

    【讨论】:

    • 是的,很好,我会这样访问,但问题是我不希望 MedicalCoverage 成为 ContractEmployee 类的一部分,而且我希望从 Employee 继承医疗保险。那么我该如何实现呢?
    • 当它不是它的有效属性时,为什么要在 Employee 中使用它。
    • 这样,如果未来的合同员工获得医疗保险,我就可以使用它。我不确定我们是否可以以这种方式隐藏,但我想知道是否有更好的方法
    • 那么我猜目前 ContractEmployee 可以有一个 MedicalCoverage 属性并且可以返回 0.0,并且将来您可以更改该值。
    • 这是“有关系”的唯一可能解决方案。如果你想单独实现它,那么你应该将 MedicalCoverage 属性包装在一个接口中,并且只为 PermanantEmployee 实现它。一旦 ContractEmployee 获得 MedicalCoverage 方案,在 ContractEmployee 类中也实现接口。
    猜你喜欢
    • 2010-11-23
    • 1970-01-01
    • 2011-09-29
    • 2010-11-27
    • 1970-01-01
    • 2015-04-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多