开发者

How to implement a fixed-sze generic IList in C#

I'm building a special collection that needs to implement the generic IList<> interface. The thing is, I want the collection to act like a non-generic fixed-size IList. I don't want the user to be able to insert or remove objects into the collection.

The IList interface doesn't implement the IsFixedSize property for some reason. So what's the best way to do this with the generic IList interface? I could just let the Insert, Remove and RemoveAt methods throw NotImplementedException, and I'd be OK with that, but is the开发者_开发问答re a better, more accepted way?

Tony


If you don't want the size of the 'list' to be changeable then just use an array.

If you don't want the collection to be editable use a ReadOnlyCollection<T>.


One typical way would be to explicitly implement the offending members of IList like Add, Insert, and Remove, so that they aren't available to people unless they actually cast your thing to IList. That's how arrays do it.


You can use a ReadOnlyCollection<T> which is a wrapper over your IList<T> that only allows reading the content but no addition or deletion:

var myList = new List<string>();
var readonlyList = new ReadOnlyCollection<string>(myList);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜