概要
Unity 2021.2 から Dictionary の 3 つの拡張メソッドが標準で使えるようになった
(もしかしたら Unity 2021.1 から使えるかも?)
- GetValueOrDefault
- Remove
- TryAdd
using System.Collections.Generic; using UnityEngine; public class Example : MonoBehaviour { private void Start() { var dictionary = new Dictionary<int, string>(); // 3 に設定されている値を取得 // 3 に設定されている値が存在しない場合はデフォルト値を取得 Debug.Log( dictionary.GetValueOrDefault( 3 ) ); // Null // 3 に設定されている値を取得 // 3 に設定されている値が存在しない場合は "フシギバナ" を取得 Debug.Log( dictionary.GetValueOrDefault( 3, "フシギバナ" ) ); // フシギバナ // 3 にフシギバナを登録 // 登録できたので戻り値で true が返ってくる Debug.Log( dictionary.TryAdd( 3, "フシギバナ" ) ); // True // 3 にヒトカゲを登録 // 既に 3 にフシギバナが登録されているため何も起きず // 戻り値で false が返ってくる Debug.Log( dictionary.TryAdd( 3, "ヒトカゲ" ) ); // False Debug.Log( dictionary[ 3 ] ); // フシギバナ // 3 に設定されている値を取得してから削除 // 削除できたので戻り値で true が返ってくる Debug.Log( dictionary.Remove( 3, out var result1 ) ); // True Debug.Log( result1 ); // フシギバナ // 3 に設定されている値を取得してから削除 // 既に 3 に設定されている値は削除されているため // 戻り値で false が返ってくる Debug.Log( dictionary.Remove( 3, out var result2 ) ); // False Debug.Log( result2 ); // Null } }
もしも独自で GetValueOrDefault を拡張メソッドで定義するなどしていると
独自の拡張メソッドと System.Collections.Generic の拡張メソッドが競合して
Unity 2021.2 にアップデートした時にコンパイルエラーが発生する可能性がある