【问题标题】:Declare a varible or property as "BaseClassType" and also require it to implement an interface?将变量或属性声明为“基类类型”并且还要求它实现接口?
【发布时间】:2015-06-26 00:03:50
【问题描述】:

是否可以在 vb.net 中将成员变量或属性声明为某个也恰好实现接口的派生类?我的意思是给定的:

Class Shape
    ...
End class

Class Cube
    Inherits Shape
    ...
End Class

Class Sphere
    Inherits Shape
    Implements IRollable
    ...
End Class

Class Cylinder
    Inherits Shape
    Implements IRollable
    ...
End Class

我可以声明一个属性或“类级别变量”(它们在 vb.net 中是否有特定名称)是一个形状(球体或圆柱体)但不是立方体?

'This is what I want to do
Class A
    Dim roller1 as Shape And IRollable
    'Or
    Property roller2 (Of RollingShape) as {Shape, IRollable}
End Class 

如果这样的事情是不可能的,那么在 vb.net 或 .net 框架中是否存在架构上的原因?

我想我可以做这个空类并让另一个类都继承它,但这看起来又乱又丑:

Class RollableShape
    Inherits Shape
    Implements IRollable
End Class

【问题讨论】:

  • ISpherical which 实现了 Cube 未实现的 IRollable。如果 Sphere 和 Cube 有共同点,我会将 Shape 保留为 Type。 RollableShape 可以从 shape 继承并实现 ISpherical 和扩展,IRollable(现在可能是同义词)
  • 根据自己的要求,RollableShape 类的思路似乎是需要的。我猜你想确保它是一个抽象类 (MustInherit)。

标签: .net vb.net oop inheritance


【解决方案1】:

如何定义一个 IShape 接口并让 IRollable 从中派生?

Interface IShape
...
End Interface

Interface IRollable Inherits IShape
...
End Interface

Class Shape Implements IShape
...
End Class

Class Sphere Inherits Shape Implements IRollable
...
End Class

Class A
  Dim roller As IRollable
End Class

这种方式 A 只依赖于 IShape 和 IRollable 等接口。

【讨论】:

    猜你喜欢
    • 2016-03-22
    • 1970-01-01
    • 1970-01-01
    • 2021-11-22
    • 2013-11-13
    • 2023-04-05
    • 2019-10-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多