簡體   English   中英

如何獲取數組中每個 object 的屬性?

[英]How do I get properties for each object in the array?

我正在嘗試寫一個紙牌游戲,我有這個問題。

我有一個List<int> address 1 Player; 其中包含一組帶參數的卡片。

我需要從這張表中提取每張卡的參數。

例如, List<int> address1Player包含 id 為 1、2、3 的卡片。我需要找出List<int> adress1Player中卡片的 colors 是什么。 Colors 存儲在int中。

顏色獲取參數如下所示

public int PropertyColor(int adress){
    return  allProperties [adress].GetComponent<Plot> ().GetColor ();
}

如何確保我最終得到一個包含每張卡的 colors 的陣列?

List<int>僅包含整數列表-在您的情況下為ID。 您想存儲 colors 的數據結構(表面上,還有一些關於卡片的其他值),因此List不是您想要的集合。 首先,讓我們考慮一下我們的集合將持有的數據結構,然后我們將回到集合。

我們游戲中的卡片至少有兩個屬性:ID 和基於 integer 的顏色。 在 C# 中,我們編寫類或結構來將屬性的邏輯包分組到 object 中。 它看起來(很簡單)是這樣的:

public struct KorsunsCard
{
   public int Id;
   public int CardColor
}

現在,我們有一個“卡片”object,它具有我們可以檢查和設置的屬性,如下所示:

KorsunsCard greenCard = new KorsunsCard() { Id = 1, CardColor = 6 };
greenCard.CardColor = 5; // change the color to "5"
if (greenCard.Id == 2) { .. do some stuff }

然后,我們可以讓方法返回整張卡片:

public KorsunsCard GetCardWithID(int Id) 
{
    KorsunsCard returnCard = ...
    ... we'll get to this part in a moment ...
    return returnCard;
}

現在,關於那些 collections。 選擇要使用的數據結構是 C# 的核心。 Collections 是對象的“組”——在我們的例子中是KorsunsCard s。 每個集合都可以做好不同的事情 - List可以通過“索引”(而不是 Id)訪問卡片,遍歷整個列表,對自己進行排序等。 Dictionary用於通過鍵查找卡片,並且雖然它們可以遍歷整個字典,但它們通常並不適用於此,因此語法涉及更多。 不難,只是不如List容易。 您可能還需要一個HashSet ,一個只能有一個唯一項目的集合 - 但沒有排序,就像字典一樣。

我不能建議最好的解決方案,因為這取決於你的游戲規則(你的牌組總是有相同數量的牌嗎?每種牌只有一張?用戶是否從可用牌池中構建自己的牌組? ?)。

讓我們從一些卡片開始:

KorsunsCard ace = new KorsunsCard() { Id = 1, Color = 1 };
KorsunsCard deuce = new KorsunsCard() { Id = 2, Color = 2 };
KorsunsCard trey = new KorsunsCard() { Id = 3, Color = 3 };

如果你想要一個List ,你可以聲明它並向它添加一些值,如下所示:

List<KorsunsCard> myDeck = new List<KorsunsCard>();
myDeck.Add(ace);
myDeck.Add(deuce);
myDeck.Add(trey)

int deuceColor = deuce.Color; // deuce's color
return myDeck[0]; // ace, but be aware the list can be shuffled/sorted!

foreach (KorsunsCard kc in myDeck) // iterate on the whole deck
{
    kc.Color = 4; // set the entire decks color to 4 , one at a time
}

通用集合類型DictionaryHashSetQueueStack可能都與您的游戲相關,具體取決於您通常如何與套牌和游戲規則進行交互。 希望我已經從List中為您提供了足夠的信息,您可以 go 並閱讀這些其他集合類型並使用它們。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM