我来自VBA世界,将代码细分为类,命名空间和模块的选项是有限的.现在我刚刚进入了一个选项很多的世界,我感到迷茫. 我想知道在另一个类中声明一个类的目的是什么? (见下面的例子)
我想知道在另一个类中声明一个类的目的是什么? (见下面的例子)
Class FirstClass Public OnePropertyInside As String Class SecondClass Public AnotherProperty As String End Class End Class
如果我创建一个FirstClass的新实例(比如myFirstClass),则不会实例化SecondClass.
更为古怪(至少对我而言)是,intelissense为我提供了myFirstClass.SecondClass.显然,因为类没有实例化,所以我无法访问它的任何成员.
那么,只有当SecondClass包含共享成员时才有用吗?
为了尝试回答这个问题,我在SecondClass中添加了一个共享成员:
Class FirstClass Public OnePropertyInside As String Class SecondClass Public AnotherProperty As String Public Shared SharedProperty As String End Class End Class
我运行了一些带来次要问题的测试(参见代码中的注释)
Sub Main() Dim myFirstClass As New FirstClass 'Works as expected Console.WriteLine(myFirstClass.OneProperty) 'What is the difference between the two lines below? Console.WriteLine(myFirstClass.SecondClass.SharedProperty) Console.WriteLine(FirstClass.SecondClass.SharedProperty) 'This line cannot be compiled, this demonstrates SecondClass is not instantiated when FirstClass is. Console.WriteLine(myFirstClass.SecondClass.AnotherProperty) Dim mySecondClass As New FirstClass.SecondClass 'Works as expected, but I feel this hierarchy should better be dealt with through a namespace statement? Console.WriteLine(mySecondClass.AnotherProperty) End Sub当你这样做,并且内部类可以被其他类访问(它的可访问性是Public或Friend),外部类基本上就像命名空间一样.因此,例如,使用您的示例,您可以创建嵌套类的新对象,而无需创建外部类之一:
Dim x As New FirstClass.SecondClass()
最明显的好处是代码的结构组织,就像名称空间和代码文件一样.因此,例如,为常量使用嵌套类并不常见,以帮助更好地组织它们:
Public Class Urls Public Class Processing Public Const Submit As String = "..." Public Const Cancel As String = "..." End Class Public Class Reporting Public Const Daily As String = "..." Public Const Weekly As String = "..." End Class End Class ' ... Dim url As String = Urls.Reporting.Daily
然而,除了那些有用的东西之外,大多数人都不愿意根本不嵌套公共课.
但是,正如其他人所提到的那样,你真正看到经常使用的嵌套类的地方是私有的.如果你需要一些小的帮助器类,它们没有用来在你的类之外进行编码,那么没有理由公开它.即使您将其设置为对Friend的可访问性,它仍将对同一项目中的所有其他类可见.因此,如果您真的想要将其隐藏在其他所有内容中,您将希望将其设置为嵌套的私有类.例如:
Public Class MyClass Public Function GetTheIdOfSomething() As Integer Dim d As Details = GetDetailsAboutSomething() If d.Value Is Nothing Then Return d.Id Else Throw New Exception() End If End Sub Private Function GetDetailsAboutSomething() As Details ' ... return a Details object End Function Private Class Details Public Property Id As Integer Public Property Value As String End Class End Class