C#interface学习(二)--索引器使用

接口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()
    {

    }
}

    
    
   
   


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值