哪些方法应该被重写以正确继承' ObservableCollection '



我想创建一个连接TableObservableCollection功能的类。所以我写了:

public sealed class ObservableTable<T> : ObservableCollection<T>, ITable<T> where T : class
{
    private Table<T> _table;
    public Expression Expression => _table.AsQueryable().Expression;
    public Type ElementType => _table.AsQueryable().ElementType;
    public IQueryProvider Provider => _table.AsQueryable().Provider;
    public new IEnumerable<T> Items => _table;
    public new T this[int index] => _table.ElementAt(index);
    public new int Count => _table.Count();
    public ObservableTable(ref DataContext dbContext)
    {
        _table = dbContext.GetTable<T>();
        OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
    } 
    public void InsertOnSubmit(T entity)
    {
        _table.InsertOnSubmit(entity);
        OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add));
    }
    public void Attach(T entity)
    {
        _table.Attach(entity);
    }
    public void DeleteOnSubmit(T entity)
    {
        _table.DeleteOnSubmit(entity);
        OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove));
    }
}

但是尽管_table对象正确地从数据库中获取所有记录,当我将我的类转换为ObservableCollection时,集合是空的。我应该重写什么才能让它工作?ItemsCount属性还不够吗?

因为底层ObservableCollection<T> 为空。您正在重定向ObservableTable<T>的indexer和Count属性,以便从表中返回值,并且您通过new隐藏了原始属性实现,但是实际的集合,即ObservableCollection使用的内部存储,从未被填充。

如果您使用ObservableTable<T>原样,一切工作。但是一旦将其强制转换为ObservableCollection<T>,就会调用indexer和count属性的原始实现,它们将尝试从内部存储中检索值和计数。

你没有重写属性,你在你的类中"重新引入"它们,并且隐藏 ObservableCollection<T>的属性。查看文档或此问题。

所以如果你访问Count属性作为((ObservableCollection<T>)instanceOfObservableTable).Count,你实际上得到隐藏的Count属性的基类,而不是你的"重新引入"的属性。你可以这样访问你的属性:((ObservableTable<T>)instanceOfObservableTable).Count .

Count属性不是虚拟的,所以你不能覆盖它。

我建议你实现INotifyCollectionChangedINotifyPropertyChanged接口在你的类,所以你可以使用它作为一个可观察的集合。

最新更新