假設我有一個名為“Class Section”的類,它有兩個屬性,即 area 和 mElement。像這樣:
Public Class ClassSection
Public Property area as double
Public Property mElement as ClassElement
End Class
現在我想在 mElement 中使用 ClassSection(父類)屬性“區域”。就像下面的代碼一樣。
Public Class ClassElement
Public Sub CalculateAreaRatio()
Dim AreaRatio as Double
AreaRatio=Area/10 'This area is ClassSection Area
End Sub
End Class
如何做到這一點。先感謝您
uj5u.com熱心網友回復:
正如我在評論中所說,您創建的每個 ClassElement 都不知道它是否包含在 ClassSection 元素中。如果您想知道這種關系的每個元素,您應該將容器傳遞給 ClassElement 實體。
所以讓我們把ClassElement結構改成這個
Public Class ClassElement
Dim myParent As ClassSection
Public Sub New(parent As ClassSection )
myParent = parent
End Sub
Public Function CalculateAreaRatio() As Double
Dim AreaRatio As Double
AreaRatio = MyParent.Area / 10 'This area is ClassSection Area
Return AreaRatio
End Function
End Class
現在,每次創建 ClassElement 時,都必須將 ClassSection 容器傳遞給建構式代碼。然后保存在私有欄位中傳遞的實體。此私有欄位可在CalculateAreaRatio 中使用。
呼叫代碼可能是這樣的
Dim section As ClassSection = New ClassSection With {
.area = 3
}
section.mElement = New ClassElement(section)
Console.WriteLine(section.mElement.CalculateAreaRatio())
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/515495.html
標籤:VB.net特性亲子父母
上一篇:碰撞后如何找到球軌跡點的變化點
下一篇:錯誤-'無法將'System.Collections.Generic.List`1[]'型別的物件轉換為'System.Collections.Generic.
