C# [] 運算符

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]就可以用於在兩種不同的內部的容器中進行檢索,並返回不同類型的值。和函數重載規則一致。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章