문제

I was wondering, why on some occasions i see a class representing some type's collection.

For example:

In Microsoft XNA Framework: TextureCollection, TouchCollection, etc. Also other classes in the .NET framework itself, ending with Collection.

Why is it designed this way? what are the benefits for doing it this way and not as a generic type collection, like was introduced in C# 2.0 ?

Thanks

도움이 되었습니까?

해결책

The examples you gave are good ones. TextureCollection is sealed and has no public constructor, only an internal one. TouchCollection implements IList<TouchLocation>, similar to the way List<T> implements IList<T>. Generics at work here btw, the upvoted answer isn't correct.

TextureCollection is intentionally crippled, it makes sure that you can never create an instance of it. Only secret knowledge about textures can fill this collection, a List<> wouldn't suffice since it cannot be initialized with that secret knowledge that makes the indexer work. Nor does the class need to be generic, it only knows about Texture class instances.

The TouchCollection is similarly specialized. The Add() method throws a NotSupportedException. This cannot be done with a regular List<> class, its Add() method isn't virtual so cannot be overridden to throw the exception.

This is not unusual.

다른 팁

In the .NET framework itself, many type-safe collections predate 2.0 Generics, and are kept for compatibility.

For several XAML-related contexts, there's either no syntax to specify a generic class, or the syntax is cumbersome. Therefore, when List<T> wiould be used, there's a specific TList written for each need.

It allows you to define your own semantics on the collection (you may not want to have an Add or AddRange method etc...).

Additionally, readability is increased by not having your code littered with List<Touch> and List<Texture> everywhere.

There is also quite a lot of .NET 1.0/1.1 code that still needs to work, so the older collections that predate generics still need to exist.

It's not that easy to use generic classes in XAML for example.

Following on from Oded's answer, your own class type allows for much easier change down the track when you decide you want a stack / queue etc instead of that List. There can be lots of reasons for this, including performance, memory use etc.

In fact, it's usually a good idea to hide that type of implementation detail - users of your class just want to know that it stores Textures, not how.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top