c# – 为什么INotifyCollectionChanged不扩展IList?
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了c# – 为什么INotifyCollectionChanged不扩展IList?,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2151字,纯文字阅读大概需要4分钟。
内容图文
![c# – 为什么INotifyCollectionChanged不扩展IList?](/upload/InfoBanner/zyjiaocheng/795/aa74e72738234285b3c91a1eb3d64fee.jpg)
我曾经遇到过几次想要通过INotifyCollectionChanged接口观察集合的情况,但也希望能够访问任何集合的元素. INotifyCollectionChanged接口不提供任何访问元素的方法,除了更改事件中涉及的那些元素(通常)包含在NotifyCollectionChangedEventArgs中.
现在这是我的想法:
>我们知道无论实现INotifyCollectionChanged是一个集合(呃).
>由于NotifyPropertyChangedEventArgs包含指示更改位置的索引,因此我们知道可以通过索引访问这些元素.
可以通过索引访问的集合是一个列表,因此似乎要求任何INotifyCollectionChanged实现者也实现IList是有意义的.这可以通过让INotifyCollectionChanged扩展IList来轻松完成.
有谁知道为什么不是这样的?
解决方法:
我认为你需要查阅SOLID软件设计原则,特别是Liskov Substitution Principle.
您问为什么INotifyCollectionChanged接口不会扩展IList接口.让我用Liskov Subsitution原则用一个反问题来回答:
Can I say an
INotifyCollectionChanged
is anIList
?
不,我不这么认为,原因如下:
> INotifyCollectionChanged传达了这样的意义:实现此接口的类需要通知其用户是否更改了其底层集合,无论该底层集合是IList还是ICollection,还是IEnumerable,我们都不知道.它是IList接口的不同概念,它只是一个带有暴露的indexer的ICollection
>您提到NotifyPropertyChangedEventArgs(我认为您的意思是NotifyCollectionChangedEventArgs)会公开指示集合更改位置的索引的属性.但是,这并不意味着这些属性必然会通过IList的索引器公开项目.它可以是一个任意数字,一个魔法常数,无论如何.由实现类来决定如何公开索引.
为了演示这一点,请查看我实现INotifyCollectionChanged的自定义类:
public class MyCustomCollection : INotifyCollectionChanged
{
// This is what I meant by the "underlying collection", can be replaced with
// ICollection<int> and it will still work, or even IEnumerable<int> but with some
// code change to store the elements in an array
private readonly IList<int> _ints;
public MyCustomCollection()
{
_ints = new List<int>();
}
public event NotifyCollectionChangedEventHandler CollectionChanged;
public void AddInt(int i)
{
_ints.Add(i);
OnCollectionChanged(new NotifyCollectionChangedEventArgs(
NotifyCollectionChangedAction.Move,
(IList)_ints,
_ints.Count,
_ints.Count - 1));
}
protected virtual void OnCollectionChanged(NotifyCollectionChangedEventArgs e)
{
var handler = CollectionChanged;
if (handler != null)
{
handler(this, e);
}
}
}
希望这能回答你的问题.
内容总结
以上是互联网集市为您收集整理的c# – 为什么INotifyCollectionChanged不扩展IList?全部内容,希望文章能够帮你解决c# – 为什么INotifyCollectionChanged不扩展IList?所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。