索引函数是对属性的进一步扩展,它能够以数组的方式来控制对多个变量的读和写。说的通俗点,就是隔山打牛,你也可以直接去打牛,但是可能不好控制力度,索引器就是实现这个效果的.下面看看实现的代码:

 

 IndexerClass     
{   
   private int[] myArray = new int[100];     
   
public int this [int index] // Indexer declaration   
   {   
      
get     
      { 
//Check the index limits.   
        if(index < 0 || index >=100)   
           
return   0;   
        
else   
           
return myArray[index];   
       }   
       
set     
       {   
         
if(!(index < 0 ||index>= 100))   
            myArray[index] 
= value;   
       }   
    }   
  }   
 
public class MainClass     
  {   
    
public static void  Main()     
    {   
       IndexerClass b  
= new IndexerClass();   
       
// Call the indexer to initialize the elements #3 and #5.   
        b[3= 256;   
        b[
5= 1024;   
        
for(int i=0;i<=10;i++)     
        {   
          Console.WriteLine(
"Element #{0} = {1}", i, b[i]);   
              }   
        }   
  }  

相关文章: