using System;
using System.Collections.Generic;
using System.Text;
namespace MyConApp例4_3
{
class Program
{
private int count = 0;
private int position = 0;
private string[] strings;
public string this[int index]
{
get
{
if (index < 0 || index >= strings.Length)
{
Console.WriteLine("Error,Current item doesn't exist.");
return null;
}
else
{
return strings[index];
}
}
set
{
if (index >= 0 && index < strings.Length)
{
strings[index] = value;
if (position < index + 1)
{
position = index + 1;
count++;
}
}
else
{
Console.WriteLine("Index Error!");
}
}
}
public string this[string str]//重载索引器
{
get
{
int index=0;
for (int i = 0; i < strings.Length; i++)
{
if (strings[i].StartsWith(str))
{
index = i;
break;
}
}
return this[index];
}
set
{
int index=0;
for (int j = 0; j < strings.Length; j++)
{
if (strings[j].StartsWith(str))
{
index = j;
break;
}
this[index] = value;
}
}
}
public Program()
{
strings = new string[100];
}
public Program(params string[] init)
{
strings = new string[100];
foreach (string i in init)
{
strings[position] = i;
position++;
count++;
}
}
static void Main(string[] args)
{
Program pp1 = new Program();
Program pp2 = new Program("mestring one", "yourstring two", "himstring three");
pp2["your"] = "changed string";
Console.WriteLine(pp2["me"]);
}
}
}
这是一个索引器重载的测试程序,但程序在运行时报错,我不知道为什么?如果把红色代码去掉后,是正常的。
保留红色代码,去掉蓝色代码,在后面添加:Console.WriteLine(pp2[0]);得到的结果竟然是"changed string",简直不可思议,哪位高手帮我分析分析?非常感谢!