2010-11-26 77 views
1

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

我现在所做的就是将它们命名为相同,并用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 

谢谢你的时间。

+0

你总是可以使用一个变量类型前缀..子新(BYVAL intOffset为整数,BYVAL intLoopCount为整数) – N0Alias 2010-11-26 16:27:02

+0

@DaMartyr啊,我以前一直这样做,但被告知不再推荐使用.NET。情况并非如此吗? – Brad 2010-11-26 16:31:13

回答

3

我会做Fredou的回答这个

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 
0

更新以上参照新版本(VS2013):

你只需要编写一行来定义属性。例如:

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