5

目前,我的基础模型有以下代码:

Public Enum vehicleType
    Car
    Lorry
    Bicycle
End Enum
Public Class TrafficSurveyA
    ' Declare the fields here.
    Private fCars As Integer
    Private fBicycles As Integer
    Private fLorries As Integer

    Public Sub New()
        ' An instance of TrafficSurveyA is created with all vehicle counts set to zero.
        fCars = 0
        fBicycles = 0
        fLorries = 0
    End Sub
    Public Sub incrementCount(ByVal vehicle As vehicleType)
        ' Preconditions: none
        ' Postconditions: If vehicle is "Car", "Bicycle" or "Lorry" then 1 is added
        ' to the corresponding count. Otherwise nothing is done.

        Select Case vehicle
            Case vehicleType.Car : fCars = fCars + 1
            Case vehicleType.Bicycle : fBicycles = fBicycles + 1
            Case vehicleType.Lorry : fLorries = fLorries + 1
            Case Else 'do nothing
        End Select
    End Sub

    Public Function getCount(ByVal vehicle As vehicleType) As String
        ' Preconditions: none
        ' Postconditions: If vehicle is "Car", "Bicycle" or "Lorry", the string
        ' representation of the corresponding count is returned.
        ' Otherwise the empty string is returned.

        Dim result As String
        result = ""
        Select Case vehicle
            Case vehicleType.Car : result = Convert.ToString(fCars)
            Case vehicleType.Bicycle : result = Convert.ToString(fBicycles)
            Case vehicleType.Lorry : result = Convert.ToString(fLorries)
            Case Else : result = ""
        End Select
        Return result
    End Function

    Public ReadOnly Property Vehicles() As String
        ' Preconditions: none
        ' Postconditions: The total number of vehicles recorded is returned.
        Get
            Return (fCars + fBicycles + fLorries).ToString()
        End Get
    End Property
End Class

似乎Enum可以像这样轻松地将其放置在TrafficSurveyA类中......

Public Class TrafficSurveyA

    Enum vehicleType
        Car
        Lorry
        Bicycle
    End Enum

    ' Declare the fields here.
    Private fCars As Integer
    Private fBicycles As Integer
    Private fLorries As Integer

    Public Sub New()
        ' An instance of TrafficSurveyA is created with all vehicle counts set to zero.
        fCars = 0
        fBicycles = 0
        fLorries = 0
    End Sub
    ...
    ...

唯一的区别似乎是我需要使用 thisTrafficSurveyA.vehicleType.Lorry而不是 this的 GUI 代码vehicleType.Lorry

两者似乎都运行良好,但枚举类型的这些实现之一是错误的吗?

4

3 回答 3

4

不,两个都很好。这只是一个偏好问题,什么对组织目的最有意义。我唯一的建议是,如果枚举将在任何其他类中用作输入或输出类型,我不会把它放在这个类中。那只会令人困惑。

于 2012-12-23T17:19:57.813 回答
1

没有一个选项是错误的,但通常不鼓励公共嵌套类型(如在类中声明的枚举)。它们可能会使必须使用外部类名限定它们的客户感到困惑。在此处查看相关指南。一些相关的:

不要使用公共嵌套类型作为逻辑分组结构;为此使用名称空间。

避免公开暴露的嵌套类型。唯一的例外是嵌套类型的变量需要在罕见的场景中声明,例如子类化或其他高级定制场景。

如果类型可能在声明类型之外被引用,则不要使用嵌套类型。

于 2012-12-24T03:45:14.857 回答
0

还要考虑将范围限制在最窄的范围内:

  • Private 仅在类内部使用
  • 朋友在程序集内使用
  • Public 可以访问从该项目构建的任何项目或程序集

范围

于 2012-12-23T19:34:32.453 回答