Unity-索引器-自定义List与字典

索引器
索引器:自定义List,字典。
使用索引器主要目的:可以自己定义一个定制集合(常见自定义List,字典)

举例:此例子创建了一个可以下标为负数不崩溃的数组

索引器与“数组”的区别。
1 索引器中的索引数值,不限定为1,2,3这种数值型,类似字典。数组不行。

索引器与属性的区别
1 索引器以函数签名方式this来标识,而属性采用名称(名称可以任意)来标识
2 索引器不能用static,而属性可以
3 索引器必须有Set Get,属性可以只有Get
4 索引器可以重载,属性不能


//索引器
//索引器:自定义List,字典。
//使用索引器主要目的:可以自己定义一个定制集合(常见自定义List,字典)

//举例:此例子创建了一个可以下标为负数不崩溃的数组

//索引器与“数组”的区别。
//1 索引器中的索引数值,不限定为1,2,3这种数值型,类似字典。数组不行。

//索引器与属性的区别
//1 索引器以函数签名方式this来标识,而属性采用名称(名称可以任意)来标识
//2 索引器不能用static,而属性可以
//3 索引器必须有Set Get,属性可以只有Get
//4 索引器可以重载,属性不能
   

 
using System.Collections;
using System.Collections.Generic;   
using UnityEngine;

public class Demo : MonoBehaviour
{
    void Start()
    {
        MyArrayList myArrayList = new MyArrayList();
        myArrayList[0] = 1;

        //不报错
        Debug.Log("myArrayList[-1] = " + myArrayList[-1]);

        List<int> list = new List<int>();
        list.Add(1);
        //报错
        //Debug.Log("list[-1] = " + list[-1]);


        //更为复杂的索引器
        MyDictionary myDictionary = new MyDictionary();
        myDictionary[0] = 1;
        myDictionary[1] = 2;

        print("myDictionary[1] = " + myDictionary[1]);
        print("myDictionary[-1] = " + myDictionary[-1]);

        myDictionary["3"] = 3;
        myDictionary["0"] = 10;
        myDictionary["99"] = 199;

        print("myDictionary['3'] = " + myDictionary["3"]);
        //自己设计的索引器限制["0"]只能输出0
        print("myDictionary['0'] = " + myDictionary["0"]);
        //如下输出会报错,自己的设计的索引器不能添加索引为["99"]的数据
        //print("myDictionary['99'] = " + myDictionary["99"]);


    }

}

public class MyArrayList
{
    public List<int> list = new List<int>();
    public int this[int index]
    {
        get
        {
            if (index > 0) {
                return list[index];
            }
            return 0;
        }
        set
        {
            list.Add(value);
        }
    }

}

public class MyDictionary
{
    public List<int> list = new List<int>();
    public Dictionary<string, int> dic = new Dictionary<string, int>();
    //索引器
    public int this[int index]
    {
        get
        {
            if (index > 0)
            {
                return list[index];
            }
            return 0;
        }
        set
        {
            list.Add(value);
        }
    }
    //索引器重载
    public int this[string index]
    {
        get
        {
            if (index != "0")
            {
                return dic[index];
            }
            return 0;
        }
        set
        {
            if (index != "99")
            {
                dic.Add(index, value);
            }
        }
    }

}

在这里插入图片描述


版权声明:本文为weixin_40583225原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。