带属性的嵌套类-如何将"Set"中第一个嵌套的属性值用于第二个嵌套



对于任何使用类似查询查看此问题的人来说,重要信息

简单的答案是你不能-下面来自Plutonix的答案解释了为什么它被标记为答案

原始问题

花了一天半的时间在谷歌上搜索这个,结果一片空白!

我有以下课程:

Public Class TestClass
Dim _nestedProperty As New NestedProperty()
Private Shared Item As String
Public Property Nest1a() As NestedProperty
Get
Return _nestedProperty
End Get
Set(Value As NestedProperty)
End Set
End Property
Public Property Nest1b() As NestedProperty
Get
Return _nestedProperty
End Get
Set(Value As NestedProperty)
End Set
End Property
Public Class NestedClass
Property Nest2a As String
Get
Return sub1()
End Get
Set(value As String)
'the first value in sub 2 needs to be the name of the Nest1 property
sub2([how do i get this value],value)
End Set
End Property
Property Nest2b As String
Get
Return sub1()
End Get
Set(value As String)
'the first value in sub 2 needs to be the name of the Nest1 property
sub2([how do i get this value],value)
End Set
End Property
End Class
Shared Function sub1()
End Function
Shared Sub sub2(Nest1 As String, Value As String)
End Sub 
End Class 

事实上,第一个巢中有很多属性,我想知道哪一个在"调用"第二个巢。

即如果我使用TestClass.Nest1a.Nest2a = "abc",当从Nest2aSet调用Sub2时,我需要传入"Nest1a"而不是[how do i get this value]

我尝试在第一个嵌套的Set中设置"Item"对象,但不起作用!

在主窗体中,我用以下代码调用这个类:

Dim TC As New TestClass
TC.Nest1.Nest2a = "xyz"
'lots more code
TC.Nest1.Nest2b = "abc"

我不想每次使用TestClass时都创建一个新的实例!

有人能提出解决方案吗?

嵌套的类,而不是属性。嵌套类需要有一个对父类的引用,通常在构造函数中传递

Class Parent 
Private myChild As Foo
Public | Private | Friend Class Foo
private myPArent As Parent
Public Sub New(p as Parent)
myParent = p
End Sub
' now the nested class has a reference to the parent
Public Function xyz As Integer
Return myParent.SomeFunction * 2
End Function
...
End Class
' parent using child props:
Public Function GetFoo As integer
return myChild.Somthing
End Function
...
End Class

对于共享潜艇,您不需要参考:

Parent.Sub2

但在它们中可以做的事情有点有限(没有引用或使用实例数据)。根据道具的实际性质,这种继承有时是一种选择。您越有可能需要在其他地方创建Parent.Child类实例,就越应该考虑继承。

接口可能是另一种选择。

编辑

嵌套类通常是私有的,并用作父级的"助手"类。但如果它们是公开的,它们是可以创建的:

Dim p As New ParentFoo
Dim c As New ParentFoo.ChildBar

作为一个私有助手类,父级可以简单地使用子级来提供结果:

Dim xyz As Integer = p.BarCount

父类内部:

' the parent class may know nothing about Bars
' and uses a helper to manage them:
Public Function BarCount As Integer
return myChild.BarCount
End Function

如果父类公开子引用,您可以执行与您想要的类似的操作:

Public Property ChildFoo As Foo
Get
Return myChildFoo
End Get

现在你可以做p.ChildFoo.BarCount了。但这只是引出了一个问题,if the nested class is to be consumed externally, why is it nested?外部代码可以将myChild设置为零,直接设置props,并可能破坏父类!

最新更新