为什么要创建新的通用集合而不是使用 List?
我想制作纸牌游戏。 我需要创建一个集合来保存卡片。 我可以使用 List
类型或创建我自己的通用集合类型。
出于什么原因我应该选择创建自己的集合类型的解决方案?
更新:
1)感谢大家的快速解答。
2)实际上我需要我的卡片列表非常动态。 我需要一直添加和删除卡片。
如果我想向集合中添加专门的方法 为什么不创建我自己的继承自 List 的集合?
3)“例如,通用列表类型将允许您跳过将对象转换回卡片......”
如果我要使用 List
它也是一个通用类型,所以我不必使用铸造。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
一方面,你的牌组不应该允许你添加、删除或编辑牌。从技术上讲,它应该是一个只读数组,而不是
List
。除此之外,它可能需要专门的方法来进行洗牌、标记牌(将牌交给玩家、将牌标记为已玩过等)等等。
这完全取决于你想为此付出多少努力:)
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 :)
如果 List 为您的 api 的用户提供了太多的功能,那么您可能需要创建自己的类型。例如,如果您希望用户能够洗牌,但不希望他们移除纸牌。列表提供
Remove
、索引器list[13] = new Card
、Clear ()
,这些都会改变列表。另外,如果您想要触发特定事件,您可能需要创建自己的事件。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
, Indexerlist[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 ...
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.