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