在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
class Animal
{
private Dictionary<string, int> indexer1 = new Dictionary<string, int>();
private string[] indexer2 = new string[10];
//从indexer1取值的索引器
public int this[string index]
{
get
{
if (indexer1.ContainsKey(index))
return indexer1[index];
else
throw new Exception("未找到对应值");
}
set
{
if (indexer1.ContainsKey(index))
indexer1[index] = value;
else
indexer1.Add(index, value);
}
}
//从indexer2取值的索引器
public string this[int index]
{
get
{
if (index < 10 && !string.IsNullOrEmpty(indexer2[index]))
return indexer2[index];
else if (index >= 10)
throw new IndexOutOfRangeException();
else
throw new Exception("未找到对应值");
}
set
{
if (index < 10)
indexer2[index] = value;
else
throw new IndexOutOfRangeException();
}
}
}
class Program
{
static void Main(string[] args)
{
Animal animal = new Animal();
//第一个索引器
animal["Fish"] = 20;
animal["Tiger"] = 100;
animal["Mouse"] = 5;
//第二个索引器
animal[1] = "Dog";
animal[2] = "Cat";
animal[3] = "Bird";
}
}
|
请发表评论