1

我是一个初学者 VB.NET 程序员,我正在尝试实现一个Principal具有两个成员的类,这两个成员是两个不同类的实例。

当我正在学习如何使用事件和委托时,我想实现一个事件(如果这可以解决我的问题)以objeto2._atributoC21在分配值时进行objeto1.atributoC11更新,然后使用andPrincipal.total的所有成员的总和进行更新。object1object2

这是一个非常粗鲁的代码,但为了使这个示例尽可能清晰:

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上课,但在那种情况下,我该如何实施合适的解决方案?

4

1 回答 1

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
于 2013-02-26T19:28:24.690 回答