gpt4 book ai didi

.net - 私有(private)嵌套类

转载 作者:行者123 更新时间:2023-12-04 11:11:59 25 4
gpt4 key购买 nike

我想创建一个只能对父类可见和实例化的嵌套类。
但我也希望能够通过父类的公共(public)变量来使用嵌套类的实例。
我尝试将嵌套类设为私有(private),或将嵌套类的构造函数设为私有(private),但它不会编译。
是否可以在 .NET 中执行此操作?

这可以编译并且可以工作,但是任何人都可以使用嵌套类:

 Public Class OuterClass
Public X As Integer = 123
Public NestedClassInstance As New NestedClass(Me)

Public Class NestedClass
Private Parent As OuterClass

Public Sub New(ByVal _Parent As OuterClass)
Parent = _Parent
End Sub

Public Sub GetParentX()
Debug.WriteLine("X = " & Parent.X.ToString)
End Sub
End Class
End Class

Sub Main()
Dim OuterClassInstance As New OuterClass
OuterClassInstance.NestedClassInstance.GetParentX()
End Sub

最佳答案

通常 Private 嵌套类实现一个接口(interface)或继承另一个类,并暴露接口(interface)/基类。当您想隐藏父类的实现时,这很有用。像这样的东西:

Module EntryPoint
Sub Main()
Dim OuterClassInstance As New OuterClass
OuterClassInstance.NestedClassInstance.GetParentX()
End Sub
End Module

Public Class OuterClass
Public X As Integer = 123
Public NestedClassInstance As ISomeImplementation = New NestedClass(Me)

Private Class NestedClass
Implements ISomeImplementation
Private Parent As OuterClass

Public Sub New(ByVal _Parent As OuterClass)
Parent = _Parent
End Sub

Public Sub GetParentX() Implements ISomeImplementation.GetParentX
Debug.WriteLine("X = " & Parent.X.ToString)
End Sub
End Class
End Class

Public Interface ISomeImplementation
Sub GetParentX()
End Interface

关于.net - 私有(private)嵌套类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10937565/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com