【发布时间】:2016-10-19 16:35:47
【问题描述】:
我相信这个问题是不言自明的。我宁愿把更多的注意力放在例子上来支持问题。
public interface IEnumerable
{
IEnumerator GetEnumerator();
}
public interface ICollection : IEnumerable
{
void CopyTo(Array array, int index);
int Count { get; }
Object SyncRoot { get; }
bool IsSynchronized { get; }
}
public interface IList : ICollection
{
Object this[int index] { get; set; }
int Add(Object value);
bool Contains(Object value);
void Clear();
bool IsReadOnly { get; }
bool IsFixedSize { get; }
int IndexOf(Object value);
void Insert(int index, Object value);
void Remove(Object value);
void RemoveAt(int index);
}
很明显IEnumerable 是独立的,只允许循环遍历集合。但我不明白他们为什么将ICollection 和IList 分开?即使它们是一个,IList 也不会变胖,因为任何集合总是需要这种行为?
我看到this 帖子说,如果客户端只需要循环项目,您的 API 将返回 IEnumerable,如果只需要只读访问权限,则返回 ICollection 等等。
MSFT 为何如此完美地应用 ISP,以至于这些年来从未引起任何问题?
应用 ISP 是基于客户端代码需求的持续过程还是一次性应用程序?如果 ISP 只应用一次,那么我的问题在于帖子标题本身。
【问题讨论】:
-
我不确定是否会使用 .NET 类型作为最佳实践示例。
-
基于示例我会问为什么 IList 没有分成 2 个或更多部分。 Add+Remove 可能低于 At 和 [] 方法。
标签: c# interface-segregation-principle