【问题标题】:Class with Dictionary as a property以字典为属性的类
【发布时间】:2018-09-28 10:31:37
【问题描述】:

我知道我在这里做了一些非常模糊的事情,因为它是一段非常简单的代码,但我就是看不到它。

我有一个类,它有一个字典类型的单一属性。此类只是查找数据库表,并将一些值存储在字典属性中。麻烦的是,我在下面的代码中的 LookupValues.Add 行上得到了 System.NullReferenceException:

Public Class Lookup
    Private _LookupValues As Dictionary(Of Integer, String)

    Public Sub New(LookupToRetrieve As String)
        Dim sqlQuery As String
        sqlQuery = "SELECT * From LookupValues (NOLOCK) WHERE lookup_name = @LookupName"

        Using connection As New SqlConnection(My.Settings.PDFProcessorConnectionString)
            connection.Open()
            Using comm As New SqlCommand(sqlQuery, connection)
                comm.Parameters.Add("@LookupName", SqlDbType.VarChar, 20).Value = LookupToRetrieve

                Dim rs As SqlDataReader = comm.ExecuteReader
                Dim dt As New DataTable
                dt.Load(rs)

                For Each row As DataRow In dt.Rows
                    LookupValues.Add(row.Item("lookup_value"), row.Item("lookup_text"))
                Next
            End Using
        End Using
    End Sub

    Public Property LookupValues As Dictionary(Of Integer, String)
        Get
            Return _LookupValues
        End Get
        Private Set(value As Dictionary(Of Integer, String))
            _LookupValues = value
        End Set
    End Property
End Class

我只是看不到这里有什么问题 - 查询返回有效数据,但它不会将其添加到字典中......我做错了什么?

【问题讨论】:

标签: vb.net


【解决方案1】:

您永远不会创建字典。因此_LookupValues 将永远是Nothing

我会将LookupValues 设为只读。这意味着您不能为其分配另一个字典。这并不意味着字典本身是只读的。

Public ReadOnly Property LookupValues As New Dictionary(Of Integer, String)

您可以使用 Visual Basic 14 的 ReadOnly Auto-Implemented Properties。 IE。您不需要显式声明支持字段。

这仍然有效:

LookupValues.Add(CInt(row.Item("lookup_value")), CStr(row.Item("lookup_text")))

我也推荐使用Option Strict On

【讨论】:

  • 看,我知道我在做傻事!它所需要的只是字典声明中的“新”。感谢您的帮助:)
猜你喜欢
  • 1970-01-01
  • 2019-01-13
  • 2022-12-05
  • 2012-02-09
  • 1970-01-01
  • 1970-01-01
  • 2010-11-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多