C#索引器:在集合或数组中取出某一个元素 举例

1.语法:

[访问修饰符] 数据类型 this[参数列表]

{

        get

        { 获取索引器的内容 }

        set

        { 设置索引器的内容 }

}


2.举例

[csharp]  view plain  copy
  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>  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值