开发者

Why create new generic collection instead of using List<T>?

I want to create card game. I need to create a collection in order to hold cards. I can use the List<T> type or create my own generic collection type.

For what reasons should I choose the solution of creating my own collection type?

Update:

1) Thanks all for the quick answers.

2) Actually I need that my card list will be very dynamic. I need to add and remove cards all the time.

If I want to add specialized methods to the collection why not to create my own collection that inherit from List ?

3) "A generic list type will allow you to skip the casting of objects back to Cards for instance ..."

If I'm going to use List<T> it is also a generic type so I would not have to use开发者_运维百科 casting.


Well for one thing your deck shouldn't allow you to add, remove or edit cards. It should technically be a read-only array, not a List<>.

In addition to that, it might need specialized methods for say, shuffling, marking cards (giving them to players, marking them as played etc), and so forth.

It all depends on how much effort you want to put in this :)


If List offers the users of your api to do too much, then you might want to create your own type. For example, if you want your users to be able to shuffle the cards, but you don't want them to remove the cards. List offer Remove, Indexer list[13] = new Card, Clear () which mutate the list. Also, if you want specific events to fire, you may want to make your own.


A generic list type will allow you to skip the casting of objects back to Cards for instance ...

public class Card
{
   public Suits Suit { get; set; }
   public string Value { get; set; }

   public Card(Suits suit, string value)
   {
      this.Suit = suit;
      this.Value = value;
   }
}

public enum Suits { Heart, Spade, Club, Diamond }

// Generic List
List<Card> cards = new List<Card>();
cards.Add(new Card(Suits.Heart, "Queen"));
cards.Add(new Card(Suits.Club, "Ace"));
cards.Add(new Card(Suits.Diamond, "5"));

// List of Objects
ArrayList list = new ArrayList();
list.Add(new Card(Suits.Heart, "Queen"));
list.Add(new Card(Suits.Club, "Ace"));
list.Add(new Card(Suits.Diamond, "5"));

Console.WriteLine(String.Format("{0} {1}", cards[0].Suit, cards[0].Value));
Console.WriteLine(String.Format("{0} {1}", (list[0] as Card).Suit, (list[0] as Card).Value));

Basically it all depends on what you want. Since you know you are going to be storing cards you may as well use a generic collection.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜