zoukankan      html  css  js  c++  java
  • 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>  
  • 相关阅读:
    Day 39 管道 、数据共享与地址池
    Day 38 Semaphore ,Event ,队列
    Day37 多进程
    Day 36 网络编程-计算机的发展
    Day 35 验证客户端的合法性+socketserver
    Day 34 黏包
    Day 33 Socket编程.
    Day 32 网络编程
    Day 31 面向对象考试题 第四次考试.
    Day 30 面向对象的考试题
  • 原文地址:https://www.cnblogs.com/AdaLoong/p/5625138.html
Copyright © 2011-2022 走看看