索引器:
[访问修饰符] 返回值类型 this[任意数据类型 index] { set { } get { } }
实质:方法的变异品种
作用:访问方法从对象.方法名(参数)=>对象[参数]
自定义索引器 VS 数组索引器
(1)索引器的索引值(Index)类型不受限制
(2)索引器允许重载
(3)索引器不是一个变量
索引器 VS 属性
(1)属性以名称来表示,索引器以函数形式标识
(2)索引器可以被重载,属性不可以
(3)索引器不能声明static,属性可以
public class Student
{
//索引器
//indexer
//["name"]["age"]
public object this[string proName]
{
get
{
if (proName == "name")
{
return this.name;
}
if (proName == "age")
{
return this.age;
}
return null;
}
set
{
//"name" "age" value
if (proName == "name")
{
this.name = value as string;
}
if (proName == "age")
{
this.age = (int)value;
}
}
}
}
public class Program : MonoBehaviour
{
void Start()
{
Student s = new Student();
//s.Name = "校花";
//Debug.Log(s.Name);
//索引器的方式
s["name"] = "校花";
Debug.Log(s["name"]);
}
}