C# IList<;T>;与收藏相比<;T>;作为财产

C# IList<;T>;与收藏相比<;T>;作为财产,c#,.net,generics,C#,.net,Generics,我有一个带有内部数组字段的类。我想将这个数组作为一个属性公开,这样它可以保持原始数组的功能,但不会因为直接公开数组而违反封装。各种方法的优缺点是什么?我特别想到的是IList或学院IList是一个ICollection: public interface IList<T> : ICollection<T>, IEnumerable<T>, IEnumerable 公共接口IList:ICollection, IEnumerable,IEnumera

我有一个带有内部数组字段的类。我想将这个数组作为一个属性公开,这样它可以保持原始数组的功能,但不会因为直接公开数组而违反封装。各种方法的优缺点是什么?我特别想到的是
IList
学院

IList是一个ICollection:

public interface IList<T> : ICollection<T>, 
    IEnumerable<T>, IEnumerable
公共接口IList:ICollection,
IEnumerable,IEnumerable
您可以实现ICollection,如果将来需要IList提供更多方法,您可以在不损害客户端的情况下更改它。

IList
更好,因为它是ICollection通用接口的后代,是所有通用列表的基础接口。此外,您还可以从以下接口获得功能性

IEnumerable<T> and IEnumerable
IEnumerable和IEnumerable
这是签名:

public interface IList<T> : ICollection<T>, 
    IEnumerable<T>, IEnumerable
公共接口IList:ICollection,
IEnumerable,IEnumerable
详情见下文


就我个人而言,我会将其公开为
IEnumerable
,并让客户机决定哪一个是最好的,因为这将使您能够最自由地更改底层存储。如果您真的想使用
IList
ICollection
,出于同样的原因,我会选择
ICollection

正确的方法是公开一个封装数组的文件


如果将数组作为接口公开,恶意代码会将其强制转换回数组并修改背后的值。

相关:在公共接口中需要哪些方法?由于基础类型是数组,其长度由类固定,我主要需要通过索引枚举进行访问和赋值。我不希望用户能够添加/删除/调整不协调数组的大小。ReadOnlyCollection违反了LSP,并强制输入集合实现
IList
,这是一个非常严格的限制。@Lee:输入集合是一个数组。现在它可能是一个数组,但如果他想更改它(比如说,更改为链接列表)然后他会遇到困难,因为他公开了一个ReadOnlyCollection,但是
LinkedList
没有实现
IList
IList
似乎是最好的选择,因为它允许通过索引进行访问\分配<代码>ICollection
不支持索引。唯一的缺点是
IList
公开了
Add
Remove
方法,这些方法在调用时将抛出
NotSupportedException