//--------------------------------------
// 索引器的重载
// 索引器永远属于实例成员,所以不能为static
//--------------------------------------
using System;
using System.Collections.Generic;
using System.Collections;
namespace indexoverLoad
{
class MainClass
{
public static void Main(string[] args)
{
IndexClass indexclass = new IndexClass();
indexclass[0] = "张三";
indexclass[1] = "李四";
indexclass[2] = "王五";
Console.WriteLine(indexclass[0]);
Console.WriteLine(indexclass[1]);
Console.WriteLine(indexclass[2]);
IndexStringClass indexStringClass = new IndexStringClass();
indexStringClass[1] = "001号";
indexStringClass[2] = "002号";
indexStringClass[3] = "003号";
Console.WriteLine(indexStringClass["001号"]);
Console.WriteLine(indexStringClass["002号"]);
Console.WriteLine(indexStringClass["003号"]);
Console.ReadKey();
}
}
class IndexClass
{
private string[] name = new string[10];
public string this[int index]
{
get{return name[index];}
set
{
if(index >= 0 && index<10)
name[index] = value;
}
}
}
class IndexStringClass
{
private Hashtable name = new Hashtable();
public string this[int index]
{
get{return name[index].ToString();}
set
{
name.Add(index,value);
}
}
public int this[string _name]
{
get
{
foreach (DictionaryEntry d in name)
{
if(d.Value.ToString() == _name)
{
return Convert.ToInt32(d.Key);
}
}
return -1;
}
set
{
name.Add(value,_name);
}
}
}
}