facebook twitter hatena line email

「Unity/Csharp/Dictionary」の版間の差分

提供: 初心者エンジニアの簡易メモ
移動: 案内検索
(ページの作成:「==クラスディクショナリ== using System.Collections.Generic; Dictionary<string, Car> cars = new Dictionary<string, Car>(); Car bg1 = new Car("Lexas", 50); Car...」)
 
(ディクショナリforeach)
行21: 行21:
 
  foreach(KeyValuePair<HogeType, Button> pair in enumDict)
 
  foreach(KeyValuePair<HogeType, Button> pair in enumDict)
 
  {
 
  {
  Debug.Log (pair.Key + " " + pair.Value);
+
    Debug.Log (pair.Key + " " + pair.Value);
 
  }
 
  }
  

2025年5月7日 (水) 19:42時点における版

クラスディクショナリ

using System.Collections.Generic;
Dictionary<string, Car> cars = new Dictionary<string, Car>();
Car bg1 = new Car("Lexas", 50);
Car bg2 = new Car("Rx8", 100);
cars.Add("Lexas", bg1);
cars.Add("Rx8", bg2);
Car car = cars["Lexas"];

宣言時にデータを入れる場合

Dictionary<string, Car> cars = new Dictionary<string, Car>()
{
    { "Lexas", new Car("Lexas", 50)},
    { "Rx8", new Car("Rx8", 100)},
};

ディクショナリをenumキーで

Dictionary<HogeType, Button> enumDict = new Dictionary<HogeType, Button>();

ディクショナリforeach

foreach(KeyValuePair<HogeType, Button> pair in enumDict)
{
    Debug.Log (pair.Key + " " + pair.Value);
}

ディクショナリのキーの存在判定

if (cars.ContainsKey("Lexas")) {
    // 存在するとき
}

TryGetValueを使うとき

if (cars.TryGetValue("Lexas", out Car carvalue))
{
    return carvalue;
}
return null;

参考:https://docs.microsoft.com/ja-jp/dotnet/api/system.collections.generic.dictionary-2.trygetvalue?view=net-5.0