今天开始改学.NET
C#索引器的使用
类外部通过索引器调用内部私有属性
索引器就是一个特别的属性
首先新建一个类ItcaseClass
注意:常规情况下索引器会被编译成一个Item属性,所以在使用了索引器之后不能再写一个名为Item的属性
public class ItcaseClass
{
private string[] names = { "德龙", "海狗", "liuyang", "goubao", "jierke" };
public int Count
{
get
{
return names.Length;
}
}
public string this[int index] // 这就是索引器
{
get
{
if (index < 0 || index >= names.Length)
{
throw new AggregateException();
}
return names[index];
}
set
{
names[index] = value;
}
}
}
外部类
class Program
{
static void Main(string[] args)
{
ItcaseClass ic = new ItcaseClass();
for(int i = 0; i < ic.Count; i++)
{
Console.WriteLine(ic[i]);
}
Console.ReadKey();
}
}