I have created a class named Card and a class named CardDeck. In class CardDeck I've declared an array named deck( of type Card ) whose elements are objects of class Card. Its Card object has its own number and shape.
How can I compare for example deck[0] with deck[1] to see if these obects have the same number or the same shape?
Class CardDeck
using System;
public Class CardDeck
{
private int number_of_elements = 30;
public CardDeck()//constructor
{
int[] arrayNumber = {0,1,2,3,4,5,6,7,8,9};
string[] arrayShape = { "oval" , "diamond", "square" };
deck = new Card[number_of elements];
InitialiseDeck(arrauNumber, arrayShape);
}
private void InitialiseDeck(int[] num, string[] sha)
{
int count = 0;
for( int i = 0; i < 10; i++)
{
for(int j = 0; j < 3; j++)
{
deck[count] = new Card(num[i],sha[j]);
count++;
}
}
}
}
Class Card
using System;
public class Card
{
private int number;
private string shape;
public Card( int cardNumber, string cardShape)
{
number = cardNumber;
shape = cardShape;
}
}
You'll want to make public attributes on the Card
class that expose the number
and shape
variables. Then in code outside the Card
class reference those attributes.
For example:
public class Card
{
private int number;
private string shape;
public Card( int cardNumber, string cardShape)
{
number = cardNumber;
shape = cardShape;
}
public int Number { get { return this.number; } }
public string Shape { get { return this.shape; } }
}
Usage:
var card1 = new Card(13, "diamond");
var card2 = new Card(13, "heart");
if (card1.Number == card2.Number && card2.Shape == card2.Shape)
{
// The cards are the same
}
If all you want to do is check for equality of cards, then you can just declare what the ==
operator will do for the Card
class: https://msdn.microsoft.com/en-us/library/8edha89s.aspx
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.