C# Nested Class

本文关键字:Class Nested | 更新日期: 2023-09-27 18:33:26

我有一个类动物。在动物类中,我有一个叫做狗的另一个类的列表。

class Animal
{
  List<Dog> Dogs;
  int CountNeutedDogs;

  class Dog
  {
     // some properties
     boolean neuted;
   }
 }

该列表在任何时候都可能包含大约 500 只狗。我想有一个事件,以便在狗中绝育财产的价值发生变化时,CountNeutedDogs 会得到通知和更新。我该怎么做?

编辑

我应该解释一下列表狗绑定到数据网格。用户可以将阉割属性从 false 更改为 true,反之亦然。我有一个得到和设置的财产。因此,阉割的值可以更改,我需要更新 CountNeutedDogs 值,这就是为什么我想使用一个事件但不确定如何去做。

C# Nested Class

如果你把 CountNeutedDogs 作为一个这样的属性,它总是正确的,没有事件更新:

int CountNeutedDogs
{
    get
    {
        return this.Dogs.Where(d => d.neuted).Count();
    }
}

这是对评论的跟进:

我做了一个例子,(没有测试!!)如何通过实现ObservableCollection来解决这个问题,INotifyPropertyChanged

public class Dog : INotifyPropertyChanged
{
    private bool _isNeutered;
    public bool IsNeutered 
    {
        get { return _isNeutered; }
        set 
        {
            if (_isNeutered != value)
            {
                _isNeutered = value;
                if (PropertyChanged != null)
                    PropertyChanged(this, new PropertyChangedEventArgs("IsNeutered"));
            }
        } 
    }
    public event PropertyChangedEventHandler PropertyChanged;
}
public class Animals : INotifyPropertyChanged
{
    private ObservableCollection<Dog> _dogs = new ObservableCollection<Dog>();
    public Animals()
    {
        _dogs.CollectionChanged += Dogs_CollectionChanged;
    }

    // NOTE, I haven't checked this!! But I think it should be something like this:
    private void Dogs_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
    {
        switch (e.Action)
        {
            case NotifyCollectionChangedAction.Add:
                foreach (INotifyPropertyChanged item in e.NewItems.OfType<INotifyPropertyChanged>())
                    item.PropertyChanged += Item_PropertyChanged;
                break;
            case NotifyCollectionChangedAction.Reset:
            case NotifyCollectionChangedAction.Remove:
                foreach (INotifyPropertyChanged item in e.OldItems.OfType<INotifyPropertyChanged>())
                    item.PropertyChanged -= Item_PropertyChanged;
                break;
        }
        if (PropertyChanged != null)
            PropertyChanged(this, new PropertyChangedEventArgs("NeuteredDogsCount"));
    }
    private void Item_PropertyChanged(object sender, PropertyChangedEventArgs e)
    {
        if (PropertyChanged != null)
            PropertyChanged(this, new PropertyChangedEventArgs("NeuteredDogsCount"));
    }
    public IEnumerable<Dog> Dogs 
    { 
        get { return _dogs; } 
    }
    public int NeuteredDogsCount
    {
        get
        {
            return Dogs.Where(dog => dog.IsNeutered).Count();
        }
    }
    public event PropertyChangedEventHandler PropertyChanged;
}

因此,当集合更改时,将发送NeuteredDogsCount属性的通知。这样,有界控件将重新计算NeuteredDogsCount属性。

可以将IsNeutered更改为DependencyProperty,而不是"正常"属性。