在类中创建对象的 Vb 概念理解 [英] Vb conceptual understanding of creating objects within a class
问题描述
我想知道您是否能帮助我理解如何创建一个 Card 对象(具有值和花色)并使用其中的 52 张卡片来制作一个称为卡片组的对象.
I was wondering if you could help me understand how to create a Card object (with a value and suit) and use 52 of those cards to make an object called deck.
我已经创建了卡片类,如何初始化卡片类中的每张卡片?我应该一项一项做吗?我如何将所有这些卡片链接到一副牌.
I have created my card class how do I initialize every card inside the deck class? Should I do it one by one? How do I link all those cards to one deck.
谢谢
推荐答案
碰巧我今天早些时候确实阅读了您之前的问题.
As it happen I did read your previous question earlier today.
首先,创建一个套装枚举.
First, create a suit enum.
Public Enum Suit As Integer
Hearts = 1
Diamonds = 2
Clovers = 3
Spades = 4
End Enum
然后创建卡片类.请注意,属性是只读的,因为卡片永远不会改变其值.(如果你是魔术师,可能不是真的)
Then create the card class. Notice that the properties are read only as a card never changes its value. (Maybe not true if you're a magician)
Public Class Card
Public Sub New(suit As Suit, value As Integer)
Me.m_suit = suit
Me.m_value = value
End Sub
Public ReadOnly Property Suit() As Suit
Get
Return Me.m_suit
End Get
End Property
Public ReadOnly Property Value() As Integer
Get
Return Me.m_value
End Get
End Property
Private m_suit As Suit
Private m_value As Integer
End Class
最后,创建套牌类并填充 52 张卡片.
Finally, create the deck class and populate 52 cards.
Public Class Deck
Public Sub New()
Dim cards = New Card(52 - 1) {}
Dim num As Integer = 0
For s As Integer = 1 To 4
For v As Integer = 1 To 13
cards(num) = New Card(CType(s, Suit), v)
num += 1
Next
Next
Me.m_cards = New Collections.ObjectModel.ReadOnlyCollection(Of Card)(cards)
End Sub
Public ReadOnly Property Cards() As Collections.ObjectModel.ReadOnlyCollection(Of Card)
Get
Return Me.m_cards
End Get
End Property
Private ReadOnly m_cards As Collections.ObjectModel.ReadOnlyCollection(Of Card)
End Class
这篇关于在类中创建对象的 Vb 概念理解的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!