如何在VB.NET中获得指向属性而不是类的名称



比较下面几组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

怎么做才能使顶部段编译?

这有帮助吗?

在第二组代码中,Customer是指当前类(与Me.Customer相同)的Customer 属性。然后,您可以通过实例 m_customer访问Customer属性的Field1属性(尽管此编译将在运行时抛出异常,当您尝试访问属性Customer时,因为您没有使用new关键字设置对对象的引用)

在顶部段中,当前类不包含名为Customer的属性,因此编译器将查找当前类之外的对象。然后找到一个名为Customer。在这种情况下,它不能使用Field1属性,因为Field1是非共享成员。如果你设置Fieldshared,这将编译。

那么总结一下,你要么需要让属性共享,要么通过类

的实例访问属性

:

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

相关内容

  • 没有找到相关文章

最新更新