首页 > 解决方案 > 从 ObservableCollection 和 IList 继承的类之间的区别

问题描述

我创建了两个不同的类。一个类继承自 IList,另一个类继承自 ObservableCollection。当我们为这些类创建实例时,我得到了以下结果。

继承自 IList

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        Cells = new CellCollection();
    }

    private CellCollection cells;

    public CellCollection Cells
    {
        get { return cells; }
        set { cells = value; }
    }
}

public class CellCollection : IList<OrderInfo>
{
    public CellCollection()
    {
    }

    public OrderInfo this[int index] { get => throw new NotImplementedException(); set => throw new NotImplementedException(); }



    public bool IsReadOnly => throw new NotImplementedException();

    public int Count => throw new NotImplementedException();

    public void Clear()
    {
        throw new NotImplementedException();
    }

    public bool Contains(OrderInfo item)
    {
        throw new NotImplementedException();
    }

    public void CopyTo(OrderInfo[] array, int arrayIndex)
    {
        throw new NotImplementedException();
    }

    public IEnumerator<OrderInfo> GetEnumerator()
    {
        throw new NotImplementedException();
    }

    public int IndexOf(OrderInfo item)
    {
        throw new NotImplementedException();
    }

    public void Insert(int index, OrderInfo item)
    {
        throw new NotImplementedException();
    }

    public bool Remove(OrderInfo item)
    {
        throw new NotImplementedException();
    }

    public void RemoveAt(int index)
    {
        throw new NotImplementedException();
    }

    internal void Add(OrderInfo orderInfo)
    {
        
    }

    void ICollection<OrderInfo>.Add(OrderInfo item)
    {
        throw new NotImplementedException();
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        throw new NotImplementedException();
    }
}

为 IList 维护的实例

为 IList 维护的实例。

继承自 ObservableCollection

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        Cells = new CellCollection();
    }

    private CellCollection cells;

    public CellCollection Cells
    {
        get { return cells; }
        set { cells = value; }
    }
}

public class CellCollection : ObservableCollection<OrderInfo>
{
    public CellCollection()
    {

    }


}


不为 Observable 集合维护实例,仅维护 Count

不为 Observable 集合维护实例,仅维护 Count

你能解释一下两者的区别吗?

标签: c#wpflistmvvmobservablecollection

解决方案


当光标在变量上时,您可以看到变量名称和实例的调试标签。

默认情况下,调试标签是ToString. 对于您的 class CellList,该方法ToString来自基类Object并返回该类的名称。本次显示:CellList

属性DebuggerDisplay允许定义实例的调试标签(不是字符串)。类CellCollection继承自ObservableCollection<T>比继承自Collection<T>,并且类 Collection 使用属性 DebuggerDisplay 声明

[DebuggerDisplay("Count = {Count}")]    
public class Collection<T>: IList<T>, IList, IReadOnlyList<T>

.NET 中的所有集合都是一样的,比如 List。

如果在 class 上设置此属性CellList,您将看到相同的调试标签。


推荐阅读