2015-12-20 181 views
0

可以說我有這些類是否可以確定通過哪個對象訪問對象?

Public Class Connection 
    Private a as Node 
    Private b as Node 

    Public Property Self as Node 
    Public Property Other as Node 

    Public Sub New(a as Node, b as Node) 
     Me.a = a : Me.b = b 
     a.Connection = Me : b.Connection = Me 
    End Sub 
End Class 

Public Class Node 
    Public Connection as Connection 
End Class 

,我把它像這樣

Dim a = New Node() 
Dim b = New Node() 
Dim c = New Connection(a, b); 

所以這兩個節點共享同一個連接對象。現在我試圖找出是否可以爲Connection屬性Self和Other定義一個getter,它可以檢測它們正在訪問哪個對象並相應地更改它們的返回值?

例如一些僞代碼

Public Property Other as Node 
Get 
    If (<CalledThroughObject> = a) Then Return b 
    Return a 
End Get 

,這應該是勝負

a.Connection.Other = b 
b.Connection.Other = a 

回答

1

直接回答你的問題是:不,你不能。

但是,您可以以不同方式爲您的類建模,以實現您正在嘗試執行的操作。這裏有一個例子:

Public Class Connection 
    Private my_node As Node 
    Private other_node As Node 

    Public ReadOnly Property Self As Node 
     Get 
      Return my_node 
     End Get 
    End Property 

    Public ReadOnly Property Other As Node 
     Get 
      Return other_node 
     End Get 
    End Property 

    Public Sub New(myNode As Node, otherNode As Node) 
     Me.my_node = myNode 
     Me.other_node = otherNode 
    End Sub 
End Class 

現在Connection類有「我的節點」和「其他節點」概念的概念。這意味着每個節點將有一個Connection類的單獨實例。

這裏是Node類會是什麼樣子:

Public Class Node 
    Public Connection As Connection 

    Public Sub ConnectWith(otherNode As Node) 
     Me.Connection = New Connection(Me, OtherNode) 
     OtherNode.Connection = New Connection(OtherNode, Me) 
    End Sub 

End Class 

通知的ConnectWith方法,它允許你在一個節點與另一個連接。注意它如何爲這兩個節點創建兩個Connection對象。每個連接對象都知道哪個是「自己」節點,哪個是「其他」節點。

這裏是你將如何使用這些類:

Dim a = New Node() 
Dim b = New Node() 

a.ConnectWith(b) 

現在a.Connection.Other將指向bb.Connection.Other將指向a

相關問題