C#索引器:在集合或数组中取出某一个元素 举例 _【转】
Garmmar:
[访问修饰符] 数据类型 this[参数列表]
{
get
{ 获取索引器的内容 }
set
{ 设置索引器的内容 }
}
Eg:
1 <span style="font-size:14px;">using System; 2 using System.Collections.Generic; 3 using System.Text; 4 5 namespace IndexerUsing 6 { 7 class Photo 8 { 9 10 private string name; 11 12 public string Name 13 { 14 get { return name; } 15 set { name = value; } 16 } 17 public Photo() { } 18 public Photo(string name) 19 { 20 this.name = name; 21 } 22 } 23 class Album 24 { 25 private Photo[] _photos; 26 public Album() 27 { } 28 public Album(int count) 29 { 30 _photos = new Photo[count]; 31 } 32 public Photo this[int index] 33 { 34 get 35 { 36 if (index < 0 || index > _photos.Length) 37 return null; 38 else 39 return _photos[index]; 40 } 41 set 42 { 43 if (index < 0 || index > _photos.Length) 44 return; 45 else 46 _photos[index] = value; 47 } 48 } 49 } 50 51 class Program 52 { 53 static void Main(string[] args) 54 { 55 Album album = new Album(3); 56 Photo photo1 = new Photo("王云鹏"); 57 Photo photo2 = new Photo("黄利云"); 58 Photo photo3 = new Photo("李文平"); 59 album[0] = photo1; 60 album[1] = photo2; 61 album[2] = photo3; 62 Console.WriteLine("输入第一张照片:{0}", album[0].Name); 63 64 } 65 } 66 } 67 </span>