초기화
Dictionary<dtype,dtype> dic = new Dictionary<dtype,dtype>();
Dictionary<dtype,dtype> dic = new Dictionary<dtype,dtype>(){{key,value},{key,value}}
값할당
dic[key] = value
dic.Add(key,value)
foreach
foreach(dtype key in dic.Keys){}
foreach(dtype value in dic.value){}
foreach(KeyValuePair<dtype,dtype> kvp in dic){
Debug.log(kvp.Key);
Debug.log(kvp.Value);
}
복사
생성자 인수에 복사하고 싶은 오브젝트 지정
var dic2 = new Dictionary<dtype,dtype>(dic);
기능
bool dic.Remove(key)
해당 key,value쌍 제거
dic.Remove(key)
직렬화
유니티에서 직렬화를 제공해주지 않음.ISerializationCallbackReceiver을 이용해 직렬화 가능한 Dictionary를 구현해아함.
[System.Serializable]
public class SerializableDic<Tkey, TValue> : Dictionary<Tkey, TValue>, ISerializationCallbackReceiver
{
[SerializeField]
List<Tkey> _keys = new List<Tkey>();
[SerializeField]
List<TValue> _values = new List<TValue>();
void ISerializationCallbackReceiver.OnAfterDeserialize()
{
this.Clear();
for(int i = 0; i< Math.Min(_keys.Count, _values.Count); i++)
{
this.Add(_keys[i], _values[i]);
}
}
void ISerializationCallbackReceiver.OnBeforeSerialize()
{
_keys.Clear();
_values.Clear();
foreach(KeyValuePair<Tkey,TValue> kvp in this)
{
_keys.Add(kvp.Key);
_values.Add(kvp.Value);
}
}
void OnGUI()
{
foreach (var kvp in this)
GUILayout.Label("Key: " + kvp.Key + " value: " + kvp.Value);
}
}
'Language > C#' 카테고리의 다른 글
[C#] Reflection (1) | 2024.10.14 |
---|---|
[C#] Enum (0) | 2024.10.14 |
[C#] Abstract Class (0) | 2024.10.14 |
[C#] Orderby (0) | 2024.10.14 |
[기본] 참조(얕은 복사) (1) | 2022.09.20 |