Classes with Collections as Properties vs. Classes Inheriting Collections
Recently I used a class that inherits from a collection instead of having the collection instantiated within the class, is this acceptable or does it create unseen problems further down the road? Examples below for the sake of clarity:
public class Cars : List<aCar>
instead of something like:
public class Cars
{
List<aCar> CarList = new List<aCar>();
}
Any thoughts?
问题在于你的Cars类仍然有从List继承的接口,这可能允许你不需要的操作。
That depends on the final purpose of your class. If it is only going to work as your own implementation of a collection use inheritance. If not, include aa collection as a property. The second option is more versatile:
I misread the question previously.
I would suggest using composition instead of inheritance. If you want to be able to use all the funky LINQ stuff, by all means implement IEnumerable<T>
and perhaps even IList<T>
- but I wouldn't derive from List<T>
directly.
If you do want to get the collection stuff "for free" but still retain control, you could use CollectionBase. That still ties you down in terms of your one shot at inheritance, but at least you get more control over what happens in the collection.
链接地址: http://www.djcxy.com/p/53876.html