c# - 从 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 维护的实例。
继承自 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
你能解释一下两者的区别吗?
解决方案
当光标在变量上时,您可以看到变量名称和实例的调试标签。
默认情况下,调试标签是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
,您将看到相同的调试标签。
推荐阅读
- assembly - 标签后面是冒号还是等号气体?
- javascript - 上传单个 json 文件作为工作项的输入时出错 (DesignAutomation)
- javascript - 如何在 Materialise CSS 中过滤/搜索列表
- java - Pallindrome 字符串替换为 * 字符
- javascript - React Bootstrap 模态显示未按预期工作
- angular - 在 Angular 9 中使用 Oauth2 令牌刷新
- node.js - NodeJS Googleapis 服务帐号认证
- regex - 并在 grep 命令上使用条件
- android - 隐藏FAB时如何删除BottomAppBar中的Cutout?
- javascript - 使用“window.onload”时如何使用“require”?