索引指示器的重载

//重载索引指示器,接受不同类型的参数

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace suoyinzhishiqi
{
class OvrIndexer
{
private string[] myData;
private int size;

public OvrIndexer(int size)
{
this.size = 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;
}

}
public string this[string data]//重载
{
get
{
int count = 0;
for (int i = 0; i < size; i++)
{
if (myData[i] == data)
{
count++;
}
}
return count.ToString();
}
set
{
for (int i = 0; i < size; i++)
{
if (myData[i] == data)
{
myData[i] = value;
}

}
}

}
static void Main(string[] args)
{
int size = 10;
OvrIndexer myInd = new OvrIndexer(size);
myInd["empty"] = "no value";
myInd[9] = "Some Value";
myInd[3] = "Another Value";
myInd[5] = "Any Value";
Console.WriteLine(" Indexer Output ");
for (int i = 0; i < size; i++)
{
Console.WriteLine("myInd[{0}]:{1}", i, myInd[i]);
}
Console.WriteLine(" Number of "no value" entries: {0}", myInd["no value"]);
}
}
}

原文地址:https://www.cnblogs.com/yinyitianya/p/5678375.html