通常来说这样的使用较多:
if (dict.ContainsKey(key))
{
Value value = dict[key];
}
但是,调用次数较多时下面的写法效率更高,区别在于ContainsKey和TryGetValue之间:
public static void StartListening (string eventName, UnityAction listener)
{
UnityEvent thisEvent = null;
//如果根据Key可以找到相应的Value则为true,否则为false。
//Key:eventName
//Value:thisEvent
if (eventDictionary.TryGetValue (eventName, out thisEvent))
{
thisEvent.AddListener (listener);
}
else
{
thisEvent = new UnityEvent ();
thisEvent.AddListener (listener);
eventDictionary.Add (eventName, thisEvent);
}
}