阿宽

Nothing is more powerful than habit!
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

c# 索引器學習

Posted on 2007-10-14 22:13  宽田  阅读(579)  评论(0编辑  收藏  举报
             简单说来,所谓索引器就是一类特殊的属性,通过它们你就可以像引用数组一样引用自己的类。
             聲明方法如下(與屬性相似):
            //修飾符 类型名称 this [类型名称 参数名]
            public type this [int index]
            {
                
get
                {                    
                   
//...
                }
                
set
                {                    
                    
//...
                }
            }

             用例子簡單說明: 
        using System.Collections;

        
static void Main(string[] args)
        {
            
//調用IntBits.IntBits方法,意為將63賦給bits
            IntBits bits = new IntBits(63);
            
//獲得索引6的bool值,此時 bits[6]將調用索引器"public bool this[int index]"中的Get,值為True
            bool peek = bits[6];
            Console.WriteLine(
"bits[6] Value: {0}",peek);
            bits[
0= true;
            Console.WriteLine();

            Console.ReadKey();
        }

        
struct IntBits
        {           
            
private int bits;
            
public IntBits(int initialBitValue)
            {
                bits 
= initialBitValue;
                Console.WriteLine(bits);
            }
            
//定義索引器           
            
//索引器的“属性名”是this,意思是回引类的当前实例,参数列表包含在方括号而非括号之内。
            public bool this [int index]
            {
                
get
                {
                    
return true;
                }
                
set
                {                    
                    
if (value)
                    {
                        bits 
= 100;
                    }
                }
            }


             備注:
             所有索引器都使用this關鍵字來取代方法名。Class或Struct只允許定義一個索引器,而且總是命名為this。
             索引器允许类或结构的实例按照与数组相同的方式进行索引。索引器类似于属性,不同之处在于它们的访问器采用参数。
             get 访问器返回值。set 访问器分配值。
             this 关键字用于定义索引器。
             value 关键字用于定义由 set 索引器分配的值。
             索引器不必根据整数值进行索引,由您决定如何定义特定的查找机制。
             索引器可被重载。
             索引器可以有多个形参,例如当访问二维数组时。
             索引器可以使用百數值下標,而數組只能使用整數下標:如下列定義一個String下標的索引器
             public int this [string name] {...}
              
             属性和索引器
             属性和索引器之间有好些差别:
             类的每一个属性都必须拥有唯一的名称,而类里定义的每一个索引器都必须拥有唯一的签名(signature)或者参数列表(这样就可以实现索引器重载)。
             属性可以是static(静态的)而索引器则必须是实例成员。
             为索引器定义的访问函数可以访问传递给索引器的参数,而属性访问函数则没有参数。