public class Country{
...
public static City[] Cities; #region make an indexer
// take the indexer of the city as an indexer;
public City this[int index]
{
get
{
if (index < 5 || index >= Cities.Length)
{
Console.WriteLine("there is a problem on reference");
return null;
}
return Cities[index];
}
set
{
if (index < 0 || index >= Cities.Length)
{
Console.WriteLine("there is a problem on reference");
return;
}
Cities[index] = value;
} } //take the name of the city as an indexer;
public City this[string Name]
{
get
{
foreach (City p in Cities)
{
if (p.Name == Name)
return p;
}
Console.WriteLine("cannot find");
return null;
}
}
#endregion
}
----
Country newCou=new Country();
...for (int i=0;i<n;i++)
Country.Cities[i]=new City();
Country.Cities[i].Name="***";
Country.Cities[i].Population=***;
...
//经调试, Country.Cities[i]都已保存;
textBox1.Text=Country.Cities[str].Bame;
//报错, 无法讲string隐式转化为int;
请问索引器哪里设置错误了?
...
public static City[] Cities; #region make an indexer
// take the indexer of the city as an indexer;
public City this[int index]
{
get
{
if (index < 5 || index >= Cities.Length)
{
Console.WriteLine("there is a problem on reference");
return null;
}
return Cities[index];
}
set
{
if (index < 0 || index >= Cities.Length)
{
Console.WriteLine("there is a problem on reference");
return;
}
Cities[index] = value;
} } //take the name of the city as an indexer;
public City this[string Name]
{
get
{
foreach (City p in Cities)
{
if (p.Name == Name)
return p;
}
Console.WriteLine("cannot find");
return null;
}
}
#endregion
}
----
Country newCou=new Country();
...for (int i=0;i<n;i++)
Country.Cities[i]=new City();
Country.Cities[i].Name="***";
Country.Cities[i].Population=***;
...
//经调试, Country.Cities[i]都已保存;
textBox1.Text=Country.Cities[str].Bame;
//报错, 无法讲string隐式转化为int;
请问索引器哪里设置错误了?
textBox1.Text=Country.Cities[str].Name , 打错了,这个不重要,主要是Country.Cities[str]无法通过str引用这个city对象,只能通过index。
请帮忙看看
猪头,应该是 textBox1.Text=newCou[str].Name;
你定义的索引器是针对 Country 类的