gpt4 book ai didi

vb.net - 添加到列表中的自定义属性类别

转载 作者:行者123 更新时间:2023-12-02 06:53:45 25 4
gpt4 key购买 nike

这似乎是我应该知道的事情,也许它工作正常,但对我来说看起来是错误的。我希望将数据库查询中的一些数据添加到一个列表中,我创建了一个自定义属性类来保存该列表。

我的类(class):

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

当我声明并初始化我的列表(类)然后向其中添加数据时:

Dim NList as New List(Of MyClass)

NList.Add(New MyClass("1", "2", (1,3), "3"))

当我查看列表项时,我看到列表中有 8 个项目,而不是 4 个。其中 4 个是方法,4 个是变量。这是正确的吗?类属性如何发挥作用?我似乎通过向 4 个变量添加数据来浪费资源,如果我必须循环遍历具有 40k 行的记录集,我假设它会提高性能。这是正确的工作方式吗?我计划稍后在程序中将项目添加到列表中并使用 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"

最佳答案

在你的类(class):

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

您的类将只有一个用于该属性值的变量。在调试中,您会看到支持字段和属性接口(interface):

?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

关于vb.net - 添加到列表中的自定义属性类别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26408452/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com