学习索引器
把对象当成数组
using System;
using System.Collections;
#region//索引器: indexTest.stringList[1]=indexTest[1]
//class IndexerExample
//{
// public string[] stringList = new string[10];
// public string this[int index]
// {
// get { return stringList[index]; }
// set { stringList[index] = value.ToString(); }
// }
//}
//class Test
//{
// static void Main()
// {
// IndexerExample indexTest = new IndexerExample();
// indexTest.stringList[1] = "hello";//直接引用数组
// indexTest[2] = "beijing";//利用索引,隐式调用了set和get方法
// Console.WriteLine("{0}--{1}",indexTest[1],indexTest[2]);
// }
//}
#endregion
#region //非整数下标
class IndexerExample
{
public Hashtable list = new Hashtable();
public int this[string name]
{
get { return (int) list[name]; }
set { list[name] = value; }
}
}
class Test
{
public static void Main()
{
IndexerExample indexTest = new IndexerExample();
indexTest["fan"] = 12346;
indexTest["wen"] = 1569;
Console.WriteLine("fan--{0}",indexTest["fan"]);
}
}
#endregion
using System;
using System.Collections;
#region//索引器: indexTest.stringList[1]=indexTest[1]
//class IndexerExample
//{
// public string[] stringList = new string[10];
// public string this[int index]
// {
// get { return stringList[index]; }
// set { stringList[index] = value.ToString(); }
// }
//}
//class Test
//{
// static void Main()
// {
// IndexerExample indexTest = new IndexerExample();
// indexTest.stringList[1] = "hello";//直接引用数组
// indexTest[2] = "beijing";//利用索引,隐式调用了set和get方法
// Console.WriteLine("{0}--{1}",indexTest[1],indexTest[2]);
// }
//}
#endregion
#region //非整数下标
class IndexerExample
{
public Hashtable list = new Hashtable();
public int this[string name]
{
get { return (int) list[name]; }
set { list[name] = value; }
}
}
class Test
{
public static void Main()
{
IndexerExample indexTest = new IndexerExample();
indexTest["fan"] = 12346;
indexTest["wen"] = 1569;
Console.WriteLine("fan--{0}",indexTest["fan"]);
}
}
#endregion
努力不一定成功,但放弃一定失败!