[Unity冷知识]关于Dictionary的冷知识

本文不详细介绍Dictionary的用法,只介绍一些冷门知识。

1.我们经常遇到报错 KeyNotFoundException: The given key was not present in the dictionary.这是因为字典里面没有我们要找的key导致的,所以一般在使用字典前我们都要判断下 dic.ContainsKey(),看下key存不存在。当然也可以用 dic.TryGetValue()这个函数来避免掉上面的报错。

2. 从上面我们知道,当key不存在时,我们去拿字典的value就会报错,但是有一种写法,我们可以不去拿value,直接赋值,比如

  dic[12] = 0;

这样写不会有任何问题,且等价于


  if (!dic.ContainsKey(12))
      dic.Add(12, 0);
  else dic[12] = 0;

但这是为什么呢,我们看下dictionary的代码

 public TValue this[TKey key]
    {
      get
      {
        int entry = this.FindEntry(key);
        if (entry >= 0)
          return this.entries[entry].value;
        ThrowHelper.ThrowKeyNotFoundException();
        return default (TValue);
      }
      set
      {
        this.Insert(key, value, false);
      }
    }

原来dictionary里面的[]是一个索引器,这样正好印证了我们上面的现象。当我们去拿value的时候其实就是去get,当拿不到值就会报错KeyNotFound,而当我们赋值的时候,其实是在Insert,所以其实当key不存在的时候直接赋值也没什么问题。

 private void Insert(TKey key, TValue value, bool add)
    {
      if ((object) key == null)
        ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key);
      if (this.buckets == null)
        this.Initialize(0);
      int num = this.comparer.GetHashCode(key) & int.MaxValue;
      int index1 = num % this.buckets.Length;
      for (int index2 = this.buckets[index1]; index2 >= 0; index2 = this.entries[index2].next)
      {
        if (this.entries[index2].hashCode == num && this.comparer.Equals(this.entries[index2].key, key))
        {
          if (add)
            ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_AddingDuplicate);
          this.entries[index2].value = value;
          ++this.version;
          return;
        }
      }
      int index3;
      if (this.freeCount > 0)
      {
        index3 = this.freeList;
        this.freeList = this.entries[index3].next;
        --this.freeCount;
      }
      else
      {
        if (this.count == this.entries.Length)
        {
          this.Resize();
          index1 = num % this.buckets.Length;
        }
        index3 = this.count;
        ++this.count;
      }
      this.entries[index3].hashCode = num;
      this.entries[index3].next = this.buckets[index1];
      this.entries[index3].key = key;
      this.entries[index3].value = value;
      this.buckets[index1] = index3;
      ++this.version;
    }

 

你可能感兴趣的:(小技巧,unity)