C#如何比较作为数组元素的对象属性?

时间:2015-10-17 16:20:52

标签: c# arrays object compare

我创建了一个名为Card的类和一个名为CardDeck的类。 在CardDeck类中,我声明了一个名为deck(类型为Card)的数组,其元素是Card类的对象。 它的Card对象有自己的数字和形状。

如何比较deck [0]和deck [1]以查看这些对象是否具有相同的数字或相同的形状?

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++;
         }
      }
    }
}

班级卡

using System;
public class Card
{
   private int number;
   private string shape;

   public Card( int cardNumber, string cardShape)
   {
      number = cardNumber;
      shape = cardShape;
   }
}

1 个答案:

答案 0 :(得分:1)

您希望在公开Cardnumber变量的shape类上创建公共属性。然后在Card类之外的代码中引用这些属性。

例如:

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; } }
}

用法:

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
}

如果您要做的就是检查卡片的相同性,那么您只需声明==运算符将对Card类执行的操作:https://msdn.microsoft.com/en-us/library/8edha89s.aspx