C# [] 运算符

来源:互联网 发布:北京优化公司 编辑:程序博客网 时间:2024/04/30 05:40
using UnityEngine;using System.Collections;using System.Collections.Generic;namespace UGUI {    [System.Serializable]    public class InventoryItemData    {        public int slot_position;        public int item_id;        public int count;    }    [System.Serializable]    public class Inventory    {        Dictionary<int, InventoryItemData> slot_index = new Dictionary<int, InventoryItemData>();        /// <summary>        /// 通过 inventory[slot_id]的方式,去访问slot成员        /// </summary>        /// <param name="id">想要访问的格子id</param>        /// <returns>InventoryItemData,如果id不存在,则会返回空</returns>        public InventoryItemData this[int id]        {            get            {                InventoryItemData result = null;                slot_index.TryGetValue( id, out result);                return result;            }        }    }}


前几天自己写了一个UGUI的背包,突然忘记了如何重载[]运算符。

于是查了查,记录一下。

public ValueType this[ KeyType key  ]

{

get

{

return ...

}

}


另外,只要this的KeyType的类型不同,是可以重载的,比如inventory[int_id] 或 inventory[String_ID]就可以用于在两种不同的内部的容器中进行检索,并返回不同类型的值。和函数重载规则一致。