使用Readonly List属性

时间:2016-01-26 10:21:20

标签: vb.net

Gyzz我尝试使用只读列表(Of Points)属性创建用户控件。我在初始化和使用该属性时遇到了麻烦!帮助我,我对visual basic非常陌生。

的UserControl1:

Public Class PointEntryPanel

Dim P as List(of PointF) = New List(Of PointF)
Public ReadOnly Property Points as List(Of PointF)
    Get
        P = Points
        return P
    End Get
End Property

End Class

形式:

Public Class Form1

Private Sub Form1_MouseDoubleClick(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles Me.MouseDoubleClick


    ListBox1.Items.Add("You see ,No null reference exceptions")
    ListBox1.Items.Add("I want a property just like this")
    PointEntryPanel1.Points.Add(New PointF(0, 0))  'While this creates exceptions
    PointEntryPanel1.Points.Add(New PointF(1, 1))  'And the point is not added to the PList
    MessageBox.Show(PointEntryPanel1.PArray.ToString) 'this shows an empty box

End Sub

End Class

我想编写一个属性,就像'物品'列表框控件中的属性

2 个答案:

答案 0 :(得分:1)

您必须实例化P,然后在属性

中返回它
Private p As New List(of PointF)
Public ReadOnly Property Points as List(Of PointF)
    Get
        return p
    End Get
End Property

答案 1 :(得分:0)

您必须实例化新列表(T)。 使用“new”来执行此操作。

例如:

   Private Points As New List(Of Point) 'instantiate the List(of T)


Public ReadOnly Property AllPoints As List(Of Point)
    Get
        Return Points
    End Get
End Property

您也可以这样做:

Public ReadOnly Property GetAllPoints As List(Of String)
    Get
        Return Points
    End Get
End Property 
'property only to return the List (for instance visible to
'users if you want to create a classlibrary.)



Private Property AllPoints As List(Of String)
    Set(value As List(Of String))
        If (Points.Equals(value)) Then Exit Property
        Points.Clear()
        Points.AddRange(value.ToArray)
    End Set
    Get
        Return Points
    End Get 'return the points
End Property
'Property to set and get the list (not visible in a classlibrary because it  
is private)
'this can be used in the class you have pasted it only.