using System;
using System.Collections.Generic;
using System.Text;
namespace indexer_索引指示器_
{
#region 索引指示器 示例一
//class Program
//{
// static void Main(string[] args)
// {
// Indexers index = new Indexers();
// index[0] = "1";
// index[3] = "3";
// index[5] = "5";
// for (int i = 0; i < 6; i++)
// {
// if (index[i] == null)
// {
// index[i] = "空值";
// }
// //else
// //{
// // index[i] = 1;
// //}
// Console.WriteLine(index[i]);
// }
// Console.ReadKey();
// }
//}
//class Indexers
//{
// string[] s_name = new string[8];
// int[] s_sex = new int[8];
// public string this[int nIndex]
// {
// get
// {
// return s_name[nIndex];
// }
// set
// {
// s_name[nIndex] = value;
// }
// }
// //public int this[int nIndex]
// //{
// // get
// // {
// // return s_sex[nIndex];
// // }
// // set
// // {
// // s_sex[nIndex] = value;
// // }
// //}
//}
#endregion
#region 示例二
//class Program
//{
// private string[] myData;
// public Program(int size)
// {
// myData = new string[size];
// for (int i = 0; i < size; i++)
// {
// myData[i] = "empty";
// }
// }
// public string this[int pos]
// {
// get
// {
// return myData[pos];
// }
// set
// {
// myData[pos] = value;
// }
// }
// static void Main(string[] args)
// {
// int size = 10;
// Program myInd = new Program(size);
// myInd[9] = "Some Value";
// myInd[3] = "Another Value";
// myInd[5] = "Any Value";
// Console.WriteLine("\nIndexer Output\n");
// for (int i = 0; i < size; i++)
// {
// Console.WriteLine("myInd[{0}]: {1}", i, myInd[i]);
// }
// Console.ReadKey();
// }
//}
#endregion
#region 示例三
class Indexer
{
public int size;
public string[] m_data;
public Indexer(int count1)
{
size = count1;
m_data = new string[count1];
for (int i = 0; i < count1; i++)
{
m_data[i] = "empty";
}
}
public string this[int count2]
{
set
{
m_data[count2] = value;
}
get
{
return m_data[count2];
}
}
public string this[string count3]
{
set
{
for (int i = 0; i < size; i++)
{
if (m_data[i] == count3)
{
m_data[i] = value;
}
}
}
get
{
int count = 0;
for (int i = 0; i < size; i++)
{
if (m_data[i] == count3)
{
count++;
}
}
return count.ToString();
}
}
}
class Program
{
static void Main(string[] args)
{
Indexer index = new Indexer(10);
index[2] = "one";
index[4] = "two";
index[8] = "three";
index["empty"] = "four";
for (int i = 0; i < 10; i++)
{
Console.WriteLine("............{0}", index[i]);
}
Console.WriteLine("*****count*******{0}", index["four"]);
Console.ReadKey();
}
}
#endregion
#region 索引指示器与属性
/*
*
* 属性:1。允许调用方法,如同它们是公共数据成员。2。可通过简单的名称进行访问。3。可以为静态成员或实例成员。4。属性的 get 访问器没有参数。5。属性的 set 访问器包含隐式 value 参数。
* 索引器:1。允许调用对象上的方法,如同对象是一个数组。2。可通过索引器进行访问。3。必须为实例成员。4。索引器的 get 访问器具有与索引器相同的形参表。5。除了 value 参数外,索引器的
* set 访问器还具有与索引器相同的形参表
*
* 索引指示器并不难使用。它们的用法跟数组相同。在一个类内部,你可以按照你的意愿来管理一组数据的集合。这些对象可以是类成员的有限集合,也可以是另外一个数组,或者是一些复杂的数据结构。
* 不考虑类的内部实现,其数据可以通过使用索引指示器来获得
*/
#endregion
}