【问题标题】:Inheriting properties without inheritance继承属性而不继承
【发布时间】:2014-02-03 21:44:23
【问题描述】:

我在这里有一个奇怪的问题,我想答案是否定的,但是...有没有办法继承一个类的属性不继承它,只是通过组合?

我现在得到的是这样的:

Public Class Mixer
    Inherits SomeOtherClass

    Private _motor As Motor

    Public Property Active() As Boolean
        Get
            Return _motor.Active
        End Get
        Set(ByVal value As Boolean)
            _motor.Active = value
        End Set
    End Property
    Public Property Frecuency() As Boolean
        Get
            Return _motor.Frecuency
        End Get
        Set(ByVal value As Boolean)
            _motor.Frecuency = value
        End Set
    End Property

    'More properties and functions from Mixer class, not from Motor
    '
    '
End Class

所以我需要 Mixer 类来公开显示它的所有 Motor 属性,但我不想继承 Motor,因为它已经从 SomeOtherClass 继承。有没有更快、更干净、更简单的方法?

谢谢!

编辑: 只是为了澄清:我知道我可以使用一个接口,但是由于所有类的 Motor 实现都是相同的,我想直接继承它的属性,而不必在每个具有 Motor 的类中再次实现它们......但没有继承 Motor。

【问题讨论】:

  • 是的,当然,但是实现一个接口会让我编写接口的所有属性实现,而这正是我想要避免的......
  • 如果你只是让MotorMixer 实现一个通用接口,比如IMotor,那么你的代码现在的样子是一个完美的解决方案。
  • Mixer 可以继承 SomeOtherClassWithMotor 继承 SomeOtherClass 并添加一个电机。
  • Lotus 有。如果您要为很多东西添加电机,您可以创建一个 IMotor 接口,并创建继承您想要的抽象类并另外为您实现电机的属性。您的 Mixer 类将简单地从 SomeClassWithMotor 继承。不过,您必须询问您要购买的所有复杂性。

标签: vb.net inheritance composition


【解决方案1】:

我相信您可以在接口中使用属性,然后实现该接口。

看看这个question

【讨论】:

    【解决方案2】:

    您始终可以将私有 _motor 设为公共属性,然后您就可以间接访问 Motor 属性。我知道这不是你想要的。

    【讨论】:

      【解决方案3】:

      最广泛接受的解决方案(如果不是唯一的解决方案)是提取一个通用接口,该接口在包装Motor 实例的每个类中实现。

      Public Interface IMotor
      
          Property Active As Boolean
      
          Property Frequency As Boolean
      
      End Interface
      
      
      Public Class Motor
          Implements IMotor
      
          Public Property Active As Boolean Implements IMotor.Active
      
          Public Property Frequency As Boolean Implements IMotor.Frequency
      
      End Class
      
      
      Public Class Mixer
          Inherits SomeOtherClass
          Implements IMotor
      
          Private _motor As Motor
      
          Public Property Active() As Boolean Implements IMotor.Active
              Get
                  Return _motor.Active
              End Get
              Set(ByVal value As Boolean)
                  _motor.Active = value
              End Set
          End Property
      
          Public Property Frequency() As Boolean Implements IMotor.Frequency
              Get
                  Return _motor.Frequency
              End Get
              Set(ByVal value As Boolean)
                  _motor.Frequency = value
              End Set
          End Property
      
      End Class
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-05-08
        • 2012-08-15
        • 2010-10-05
        • 1970-01-01
        • 2015-03-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多