我对OO编程很陌生。我正在VB.NET中建立一个类,并且我希望属性可以在某些类别中分组。应该将类别声明为子类还是属性?换句话说,这两种方法哪一种更好?
Class Tree
Property Trunk As Trunk
Property Leaves As Leaves
End Class
Class Trunk
Property Color As String
Property Diameter As Integer
End Class
Class Leaves
Property Color As String
Property Width As Integer
Property Height As Integer
End Class
或
Class Tree
Class Trunk
Property Color As String
Property Diameter As Integer
End Class
Class Leaves
Property Color As String
Property Width As Integer
Property Height As Integer
End Class
End Class
在两种情况下,我都将Tree
的实例与myTree.Trunk.Color = "Red"
之类的东西一起使用,但是哪个实例被认为是最佳实践?
谢谢您的帮助。
答案 0 :(得分:0)
这取决于您要具有的可重用性。在您的示例中,第一种方法允许您将Trunk和Leaves类用于另一个类,例如花朵。
Class Flower
Property Trunk As Trunk
Property Leaves As Leaves
End Class
Class Tree
Property Trunk As Trunk
Property Leaves As Leaves
End Class
当然,您可以重用内部类(您的第二个示例),但是您可能必须调整范围,并且在可能使事情复杂化的大型项目中,无论如何,如果您遵循第二种方法,则应将Flower类声明为如下:
Class Flower
Property Trunk As Tree.Trunk
Property Leaves As Tree.Leaves
End Class
您可以看到区别。
您应该记住的另一件事是继承。在您的示例中,您可以将植物类声明如下:
Class Plant
Class Trunk
Property Color As String
Property Diameter As Integer
End Class
Class Leaves
Property Color As String
Property Width As Integer
Property Height As Integer
End Class
Property Trunk As Trunk
Property Leaves As Leaves
End Class
然后您可以从另一个类继承它:
Class Tree
Inherits Plant
'extra tree properties here
End Class
Class Flower
Inherits Plant
'extra flower properties here
End Class
这样,Tree和Flower类都将具有Trunk和Leaves属性:
Tree.Trunk.Color
'...
Flower.Leaves.Width
希望这会有所帮助!