1.语法:
[访问修饰符] 数据类型 this[参数列表]
{
get
{ 获取索引器的内容 }
set
{ 设置索引器的内容 }
}
2.举例
- <span style="font-size:14px;">using System;
- using System.Collections.Generic;
- using System.Text;
- namespace IndexerUsing
- {
- class Photo
- {
- private string name;
- public string Name
- {
- get { return name; }
- set { name = value; }
- }
- public Photo() { }
- public Photo(string name)
- {
- this.name = name;
- }
- }
- class Album
- {
- private Photo[] _photos;
- public Album()
- { }
- public Album(int count)
- {
- _photos = new Photo[count];
- }
- public Photo this[int index]
- {
- get
- {
- if (index < 0 || index > _photos.Length)
- return null;
- else
- return _photos[index];
- }
- set
- {
- if (index < 0 || index > _photos.Length)
- return;
- else
- _photos[index] = value;
- }
- }
- }
- class Program
- {
- static void Main(string[] args)
- {
- Album album = new Album(3);
- Photo photo1 = new Photo("王云鹏");
- Photo photo2 = new Photo("黄利云");
- Photo photo3 = new Photo("李文平");
- album[0] = photo1;
- album[1] = photo2;
- album[2] = photo3;
- Console.WriteLine("输入第一张照片:{0}", album[0].Name);
- }
- }
- }
- </span>