2013-02-26 19 views
1

我是一名初學VB.NET程序員,我試圖用兩個成員實現一個類Principal,這兩個成員是兩個不同類的實例。Visual Basic .NET中的自動調優屬性

由於我學習如何使用事件和委託我想實現一個事件(如果這可能是一個解決我的問題)來更新objeto2._atributoC21當值分配給objeto1.atributoC11,然後用總和更新Principal.totalobject1object2的所有成員。

這裏是一個非常粗魯的代碼,但使這個例子明確的,因爲這將是可能的:

Public Class Principal 
    Public objeto1 As ClaseIncluida1 
    Public objeto2 As ClaseIncluida2 
    Public total As Integer 
End Class 

Public Class ClaseIncluida1 
    Private _atributoC11 As Integer 
    Public _atributoC12 As Integer 

    Public Property atributoC11 As Integer 
     Get 
      Return _atributoC11 
     End Get 
     Set(ByVal value As Integer) 
      _atributoC11 = value 
     End Set 
    End Property 
End Class 

Public Class ClaseIncluida2 
    Public _atributoC21 As Integer 
    Public _atributoC22 As Integer 
End Class 

我知道如何使用事件和委託以簡單的方式,但是當我試圖做什麼我上面已經描述過,我發現自己陷入死衚衕。

也許事件和代表不適合Principal類,但在這種情況下,我該如何實現一個合適的解決方案?

回答

0

有沒有自動內置的方式做這種事情。如果你想這樣做,你需要自己實施管道。標準的做法是通過讓「孩子」班,如果你願意,實現INotifyPropertyChanged接口。然後,「父母」班級可以收聽他們的PropertyChanged事件。當任何一個子對象引發該事件時,父對象可以適當地處理它。在你的情況下,你想要通過更新total來處理它。例如:

Public Class Principal 
    Public WithEvents objeto1 As ClaseIncluida1 
    Public WithEvents objeto2 As ClaseIncluida2 
    Public total As Integer 

    Private Sub PropertyChangedHandler(sender As Object, e As PropertyChangedEventArgs) Handles objeto1.PropertyChanged, objeto2.PropertyChanged 
     total = ... 
    End Sub 
End Class 

Public Class ClaseIncluida1 
    Implements INotifyPropertyChanged 

    Private _atributoC11 As Integer 
    Public _atributoC12 As Integer 

    Public Property atributoC11 As Integer 
     Get 
      Return _atributoC11 
     End Get 
     Set(ByVal value As Integer) 
      _atributoC11 = value 
      RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs("atributoC11")) 
     End Set 
    End Property 

    Public Event PropertyChanged(sender As Object, e As PropertyChangedEventArgs) Implements INotifyPropertyChanged.PropertyChanged 
End Class 

Public Class ClaseIncluida2 
    Implements INotifyPropertyChanged 

    Public _atributoC21 As Integer 
    Public _atributoC22 As Integer 

    'Implement raising event when properties change 

    Public Event PropertyChanged(sender As Object, e As PropertyChangedEventArgs) Implements INotifyPropertyChanged.PropertyChanged 
End Class