比较以下几组VB.NET类:
Public Class MyProperties
Private Shared m_customer As Customer
Public Shared Property Customer() As Customer
' getter and setter code
End Property
End Class
Public Class Customer
Public Field1 As String
End Class
Public Class MyOtherClass
Sub Proc1
Debug.WriteLine(Customer.Field1) ' this does not compile
End Sub
End Class
-----------------------------------------
Public Class Customer
Public Field1 As String
End Class
Public Class MyOtherClass
Private Shared m_customer As Customer
Public Shared Property Customer() As Customer
' getter and setter code
End Property
Sub Proc1
Debug.WriteLine(Customer.Field1) ' this compiles
End Sub
End Class
可以做些什么来让顶级片段进行编译?
this可以提供帮助吗?
答案 0 :(得分:1)
在第二组代码中,Customer指的是当前类的Customer 属性(与Me.Customer
相同)。然后,您可以通过实例 Field1
访问Customer
属性的m_customer
属性(虽然这会编译它会在您尝试访问时在运行时抛出异常属性Customer,因为您尚未使用new
关键字
在顶部段中,当前类不包含名为Customer的属性,因此编译器将查找当前类之外的对象。然后它会找到一个名为Customer
的类。在这种情况下,它无法使用Field1
属性,因为Field1
是非共享成员。如果你做了Field
shared
,那就会编译。
总而言之,您需要让共享或的属性通过类的实例和
的实例来访问属性或者:
Public Class Customer
Public Shared Field1 As String
End Class
Public Class MyOtherClass
Sub Proc1
Debug.Writeline(Customer.Field1)
End SUb
End Class
或者:
Public Class Customer
Public Field1 As String
End Class
Public Class MyOtherClass
Sub Proc1
Dim myCust as New Customer
Debug.Writeline(myCust.Field1)
End SUb
End Class