1. 程式人生 > >C#interface學習(二)--索引器使用

C#interface學習(二)--索引器使用

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

//介面中的索引器
namespace Interface4
{
    interface MyInterface
    {
        string ID
        {
            set;
            get;
        }

        void SetID();

        //索引器必須以this關鍵字定義
        int this[int index] //返回值為int型別,通過int型別的下標訪問
        {
            set;
            get;
        }

        int this[string index] //返回值是int型別,通過string型別訪問
        {
            set;
            get;
        }
    }

    class MyClass : MyInterface
    {
        string id_ = "";
        public int[] num = new int[10];
        public Dictionary dic = new Dictionary();

        public int this[int index]
        {
            get
            {
                if (index < 10 && index >= 0)
                    return num[index];
                else
                    throw new IndexOutOfRangeException("獲取下標 " + index + " 越界");
            }
            set
            {
                if (index < 10 && index >= 0)
                    num[index] = value;
                else
                    throw new IndexOutOfRangeException("設定下標 " + index + " 不合法");
            }
        }

        string MyInterface.ID
        {
            get
            {
                return id_;
            }
            set
            {
                id_ = value;
            }
        }

        public int this[string index]
        {
            get
            {
                if (dic.ContainsKey(index))
                    return dic[index];
                throw new KeyNotFoundException("key值" + index + "輸入有誤");
            }
            set
            {
                dic[index] = value;
            }
        }

        public void SetID()
        {
            Debug.Log("MyClass2.SetID");
        }
    }
}

public class Interface_Test3 : MonoBehaviour
{

    // Use this for initialization
    void Start()
    {
        Interface4.MyClass m = new Interface4.MyClass();
        //直接使用索引器訪問資料
        m[1] = 1;
        //m[11] = 2; //這句會丟擲錯誤

        m["d"] = 2;
        Debug.Log(m.dic.Count);
    }

    // Update is called once per frame
    void Update()
    {

    }
}