Vb概念性理解在类中创建对象

时间:2014-02-28 17:29:30

标签: vb.net

我想知道你是否可以帮我理解如何创建一个Card对象(带有值和套装)并使用其中的52张牌制作一个名为deck的对象。

我创建了我的卡片课程如何初始化甲板课程中的每张卡片?我应该一个接一个地做吗?如何将所有这些卡片链接到一个卡片组。

由于

3 个答案:

答案 0 :(得分:3)

碰巧我今天早些时候读过你的上一个问题。

首先,创建一个套装枚举。

Public Enum Suit As Integer
    Hearts = 1
    Diamonds = 2
    Clovers = 3
    Spades = 4
End Enum

然后创建卡类。请注意,属性是只读的,因为卡永远不会更改其值。 (如果你是魔术师,也许不是真的)

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张卡片。

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

答案 1 :(得分:1)

您需要两个Enumerations和两个Classes:

  • 枚举
    1. CardFaceValue - 值范围为Ace-10(含),Jack,Queen,King。
    2. CardFaceType - 值为Hearts,Spades,Clubs,Diamonds
    1. 甲板 - 有一个属性包含所有卡的集合
      1. 卡片 - 卡片阵列,大小为52.
    2. 卡 - 有两个属性
      1. CardFaceValue
      2. CardFaceType

在Deck类的构造函数中,在循环中运行循环。对于每个CardFaceType枚举,外循环将运行4次,对于1-10,J,Q,K卡,内循环将运行13次。

使用这些循环遍历枚举值并将卡添加到您的Deck。

答案 2 :(得分:0)

这只是我想象的快速草稿

你首先需要卡片课程。

Public Class Card

    Private cSuit As String
    Private cValue As Integer

    Public Property suit() As String
        Get
            Return cSuit
        End Get
        Set(ByVal value As String)
            cSuit = value
        End Set
    End Property

    Public Property value() As Integer
        Get
            Return cValue
        End Get
        Set(ByVal value As Integer)
            value = cValue
        End Set
    End Property

    Public Sub New(ByVal TheSuit As String, ByVal TheValue As Integer)

        cSuit = TheSuit
        cValue = TheValue

    End Sub

然后,您可以为每张卡片制作一个新对象,并将其添加到卡片组合中。

Dim Deck As New List(Of Card)
        Dim Suit As String = "Spade"
        Dim Value As Integer = 11

        Dim AceOfSpades As New Card(Suit, Value)

        Deck.Add(AceOfSpades)