类构造函数中变量的命名约定

时间:2010-11-26 16:23:32

标签: vb.net naming-conventions

在我编写类和构造函数的过去,我将构造函数参数中的变量命名为与实际类本身中存储的不同。我曾经认为这让事情变得不那么混乱,但是现在我认为这实际上更令人困惑。

我现在所做的是将它们命名为相同,并使用Me.varname引用内部变量。这是我刚刚开始建设的一个班级。我的命名惯例不正确吗?

Public Class BufferPosition
    Public Offset As Integer
    Public LoopCount As Integer

    Public Sub New()

    End Sub

    Public Sub New(ByVal Offset As Integer, ByVal LoopCount As Integer)
        Me.Offset = Offset
        Me.LoopCount = LoopCount

    End Sub
End Class

感谢您的时间。

2 个答案:

答案 0 :(得分:3)

我会这样做

Public Class BufferPosition

Private _Offset As Integer
Private _LoopCount As Integer

Public Sub New()

End Sub

Public Sub New(ByVal Offset As Integer, ByVal LoopCount As Integer)
    _Offset = Offset
    _LoopCount = LoopCount
End Sub

Public Property Offset() As Integer
    Get
        Return _Offset
    End Get
    Set(ByVal value As Integer)
        _Offset = value
    End Set
End Property

Public Property LoopCount() As Integer
    Get
        Return _LoopCount
    End Get
    Set(ByVal value As Integer)
        _LoopCount = value
    End Set
End Property

End Class

答案 1 :(得分:0)

参考新版本(VS2013)更新Fredou的答案:

您只需要写一行来定义属性。示例:

Public Property Name As String

Visual Basic将自动定义一个名为_Offset的(内部)私有变量。因此,您也不需要编写显式的Get-Set语句。所以,简单来说,上面的代码替换了下面的所有代码:

Public Property Name As String
    Get
        Return _Name
    End Get
    Set(ByVal value As String)
        _Name= value
    End Set
End Property
Private _Name As String