实例化一个类,然后在相同的函数中使用它时我感到很舒服,但是现在我需要通过工具栏按钮实例化一个类:
Dim pll As New Polyline()
Debug.WriteLine("TSB_Polyline_Click:: a new polyLine is born : " & pll.Count)
pll.AddPoint(0, 0)
然后,我需要从另一个子类中的类方法运行pll.AddPoint:
Public Sub MyEvent(sender as object, e as myEvent) Handles myEvent
Dim x as Double, y as Double
pll.AddPoint(x,y)
有我的错误(System.NullReferenceException:'对象引用未设置为对象的实例。'),pll =没什么(我的构造函数中没有错误,我的类通过工具栏button_Click进行工作)
我试图将Pll声明为公开并共享:
Public Shared pll As Polyline
甚至是导入:
Imports oGIS.Polyline
没有任何作用。我的班级在第一个Sub(工具栏按钮)中得到实例化,但是以某种方式在离开Sub ...时就死了...
还有其他解决方案,使用VB6代替VB.Net吗?
我有点绝望,我在Google的任何地方都找不到这样的话题...
如果需要使用多个方法访问变量,则应在所有变量之外声明该变量。如果不需要在声明它的类型之外访问它,则应为Private
;如果您特别需要该类的所有实例访问同一对象,则应为Shared
。在您的情况下,Private
而不是Shared
是显而易见的选择:
Private pll As Polyline
您现在在第一种方法中设置了该字段,而在第二种方法中得到了。
我想对您的课程进行部分看会是这样...
Public Class Polyline
Public ReadOnly Property CountOfPoints As Integer
Get
Return ListOfPoints.Count
End Get
End Property
Public Property ListOfPoints As New List(Of Point)
Public Sub AddPoint(x As Integer, y As Integer)
Dim p As New Point(x, y)
ListOfPoints.Add(p)
End Sub
End Class
声明一个类级别(在这种情况下,该类是一个Form)变量,您的表单中的任何方法都可以看到并使用它。
Public Class Form1
Private LocalPolyLine As Polyline
'This is a local list, not part of the class
'It is a list of the number of instances of the class you have created
Private ListOfLines As New List(Of Polyline)
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
'Pretend this is a button on your toolbar used to create a new line
'Each time you click this button you have a completely new line with no points
LocalPolyLine = New Polyline
'If you want to keep track of how many lines you have...
ListOfLines.Add(LocalPolyLine)
End Sub
Private Sub AddPoint(x As Integer, y As Integer)
Debug.Print($"Number of Lines is {ListOfLines.Count}")
Debug.Print($"Number of points on current line {LocalPolyLine.CountOfPoints}")
LocalPolyLine.AddPoint(x, y)
Debug.Print($"Number of points on current line {LocalPolyLine.CountOfPoints}")
End Sub
'To see all the points on the line...
Private Sub ViewPoints()
For Each p In LocalPolyLine.ListOfPoints
Debug.Print($"The coordinates of the point are {p.X},{p.Y}")
Next
End Sub
End Class