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>  

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM