我们如何在结构上初始化List类型属性?在vb.net中

查尔斯·奥克瓦格乌(Charles Okwuagwu)

这是我尝试使用的结构:

Public Structure Point
        Public Property id As Integer
        Public Property x As Integer
        Public Property y As Integer

        Public Property Points As List(Of Point)

        Public ReadOnly Property key As String
            Get
                Return x & "," & y
            End Get
        End Property

        Public Sub Add(t As Point)
            If Points Is Nothing Then
                Points = New List(Of Point)
            End If
            Points.Add(t)
        End Sub
End Structure

下面的代码是尝试使用点结构的尝试:

Dim l = New List(Of Point)
Dim t = new Point 'test point

l.Add(t)
l(l.Count - 1).Add(t)

看l(0).locals窗口中的点,该属性始终为Nothing。

为什么是这样?

已解决:似乎以下代码有效:

Public Structure Point
    Public Property id As Integer
    Public Property x As Integer
    Public Property y As Integer

    Private _points As List(Of Point)
    Public ReadOnly Property Points() As List(Of Point)
        Get
            If _points Is Nothing Then
                _points = New List(Of Point)
            End If

            Return _points
        End Get
    End Property

    Public ReadOnly Property key As String
        Get
            Return x & "," & y
        End Get
    End Property

    Public Sub Add(t As Point)
        If _points Is Nothing Then
            _points = New List(Of Point)
        End If
        _points.Add(t)
    End Sub
End Structure

用法:

Dim l = New List(Of Point)
Dim t = new Point 'test point

t.add(t)
l.Add(t)
懒惰

我猜您谈论的错误是NullReferenceException,解决方案是在使用New关键字进行访问之前创建实例

您已经在Add方法中执行了此操作,但是您应该在构造函数中创建实例。

另外,Class如果没有充分的理由使用mutable,则应该使用a Structure


回应您的编辑:

Dim l = New List(Of Point)
Dim t = new Point 'test point

l.Add(t)
l(l.Count - 1).Add(t)

看l(0).locals窗口中的点,该属性始终为Nothing。

为什么是这样?

这就是为什么我说Structure如果您没有充分的理由不要使用可变的

如果你打电话l.Add(t)副本t将被添加到l

当你访问一个Point通过项目l(l.Count - 1).Add(t),创建另一个副本Point,再加入另一份t第二个副本

Add被称为在第二个副本t当你看l(0),你实际看到副本中的第一个副本t

如果这不是您想要的行为,请使用class

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

我们如何在golang中的结构内初始化struct类型的数组(存储json输出)

我们如何在C ++中初始化所有值为0的向量

我们如何在构造函数方法中的 react typescript 中初始化状态,如果它具有特定的接口类型

我们不能在 VB.NET 中第二次初始化字体吗?

Swift 问题:如果它是协议类型,我们如何在 if else 块中初始化一个非可选变量?

如何初始化在VB.NET中的结构内部创建的对象数组?

我们如何在 VB.net 的图片框中显示之前的图像?

我们如何在vb.net中处理大量

如何在golang中初始化以下结构的结构

如何在Go中初始化指向结构的指针的类型?

如何在VB.NET中初始化Dictionary(Of String,HashSet(Of String))?

如何在C ++中的结构中初始化向量

如何在配置文件中初始化log4net GlobalContext属性

如何在 .NET 中初始化通用对象

我们能否在Trie构造函数中初始化引用数组

为什么我们在Swift中覆盖初始化器?

我们需要在Kotlin中初始化可为空的字段吗?

为什么我们不能迅速在扩展中添加指定的初始化程序?

我们必须在Android的MvvmCross中初始化Xamarin.Forms吗?

为什么我们在构造函数中初始化对象

为什么我们不能使用scanf直接初始化struct中的变量?

如何在结构初始化中添加if语句

如何在Julia中初始化结构数组

如何在主App结构中初始化EnviromentObject?

如何在结构声明中初始化位域?

如何在Golang中初始化嵌套结构?

如何在go中初始化嵌套结构?

如何在C中初始化结构?

如何在函数中的堆上初始化静态结构?