简体   繁体   English

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

[英]C# How can I compare objects' attributes that are elements of an array?

I have created a class named Card and a class named CardDeck.我创建了一个名为 Card 的类和一个名为 CardDeck 的类。 In class CardDeck I've declared an array named deck( of type Card ) whose elements are objects of class Card.在 CardDeck 类中,我声明了一个名为deck(类型为 Card)的数组,其元素是类 Card 的对象。 Its Card object has its own number and shape.它的 Card 对象有自己的编号和形状。

How can I compare for example deck[0] with deck[1] to see if these obects have the same number or the same shape?例如,我如何比较deck[0] 和deck[1] 以查看这些对象是否具有相同的数字或相同的形状?

Class CardDeck类 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.您需要在Card类上创建公共属性,以公开numbershape变量。 Then in code outside the Card class reference those attributes.然后在Card类之外的代码中引用这些属性。

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如果您只想检查卡片是否相等,那么您只需声明==运算符将对Card类执行的操作: https : //msdn.microsoft.com/en-us/library/8edha89s.aspx

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM