这似乎是我应该知道的事情,也许它工作得很好但我看起来不对。我希望将数据库查询中的一些数据添加到一个列表中,我创建了一个自定义的属性类来保存。
我的课程:
Public Class MyClass
Private _Col1 As String
Private _Col2 As String
Private _Col3(,) As Object
Private _Col4 As String
Public Property Col1() As String
Get
Return _Col1
End Get
Set(ByVal value As String)
_Col1 = value
End Set
End Property
Public Property Col2() As String
Get
Return Col2
End Get
Set(ByVal value As String)
Col2= value
End Set
End Property
Public Property Col3() As Object(,)
Get
Return Col3
End Get
Set(ByVal value As Object(,))
Col3= value
End Set
End Property
Public Property Col4() As String
Get
Return Col4
End Get
Set(ByVal value As String)
_Col4= value
End Set
End Property
Sub New(ByVal col1 As String, ByVal col2 As String, ByVal col3 As Object, ByVal col4 As String)
_Col1= col1
_Col2= col2
_Col3 = col3
_Col4 = col4
End Sub
End Class
当我声明并初始化我的List(Class)然后向其添加数据时:
Dim NList as New List(Of MyClass)
NList.Add(New MyClass("1", "2", (1,3), "3"))
当我看一下List项时,我看到列表中有8个项而不是4. 4个是那里的方法,4个是变量。这是正确的以及类属性如何起作用?看起来我通过向4个变量添加数据来浪费资源,如果我必须遍历具有4万行的记录集,我假设它会增加性能。这是正确的方式吗?我计划在列表中添加项目,然后在程序中使用Find()函数,这样我觉得不需要8项而不是4项。
编辑:列表项
?NList.Item(0)
_Col1: "1" {String}
_Col2: "2"
_Col3: "(1,3)"
_Col4: "4"
Col3: "(1,3)"
Col4: "4"
Col1: "1"
Col2: "2"
答案 0 :(得分:2)
这是完全正常的行为。带有下划线的变量是类的成员变量。它们实际上包含您的数据。另一方面,您的属性根本不包含任何数据。您可以将它们视为将成员变量返回给调用者的函数。您也可以在直接提示中看到它们的返回值,因为它们在视觉上被视为正常变量。
在编写.Net时,通常使用成员变量和属性。 如果您没有在属性中执行任何其他代码,则可以写下:
Public Property MyProperty As SomeType
在这种情况下,编译器会自动为您生成一个不可见的相应成员变量。
答案 1 :(得分:2)
在你班上:
Public Class MyClass
Private _Col1 As String ' private backing field to hold the value
' interface to get/set that same value
Public Property Col1() As String
Get
Return _Col1
End Get
Set(ByVal value As String)
_Col1 = value
End Set
End Property
您的类只有一个属性值的变量。在调试中,您将看到支持字段和属性界面:
?NList.Item(0)
_Col1: "1" {String} <== backing field storing the value
...
Col1: "1" <== property 'exposing' _Col1
请注意,使用自动实现的属性可以大大简化您的类,并放弃显式的支持字段:
Public Class fooClass
Public Property Col1() As String
Public Property Col2() As String
Public Property Col3() As DateTime
Public Property Col4() As Integer
' VS creates hidden backing fields you can still reference in the class:
Public Sub New(str As String ...)
_Col1 = str
...
End Sub
End Class
答案 2 :(得分:1)
我修改了一些示例代码。也许这会有所帮助吗?
Public Class TestClass
Public Property Col1 As String
Public Property Col2 As String
Public Property Col3 As Object
Public Property Col4 As String
End Class
像这样添加项目
Dim NList As New List(Of TestClass)
NList.Add(New TestClass With {.Col1 = "1", .Col2 = "2", .Col3 = "3", .Col4 = "4"})
NList.Add(New TestClass With {.Col1 = "A", .Col2 = "B", .Col3 = "C", .Col4 = "D"})