第三部分 类型设计2------《Microsoft.NET框架程序设计》

  在C#中,含参属性(索引器)可以类似数组的语法来访问.换句话说,我们可以将索引器看作是重载[]操作符的一种方式.下面演示的是一个BitArray类型的例子,它允许我们用类似数组的语法来访问该类型实例中保存的一组位.

  public class BitArray  {

                        //一个用于保存位的私有字节数组

      private Byte[] byteArray;

                        private Int32 numBits;

                       //下面的构造器用于分配字节数组,并将所有的位设为0

                       public BitArray(Int32 numBits)  {

                        //首先检验参数的有效性

                        if(numBits<=0)

                            throw new ArgumentOutOfRangeException("numBits","numBits must be>0");

                         //保存位的个数

                        this.numBits=numBits;

                         //为位数组分配字节

                          byteArray=new Byte[(numBits+7)/8];

                           }

                        //下面是一个索引器

                      public Boolean this[Int32 bitPos] {

                      //下面是索引器的get访问器方法

                              get {

                                        //首先检验参数的有效性

                                          if((bitPos<0)||(bitPos>=numBits))

                                                   throw new IndexOutOfRangeException();

                                        //返回指定索引上的位的状态

                                                   return (byteArray[bitPos/8)&(1<<(bitPos%8))!=0;

                                 }

             

                          get{

                               //首先检验参数的有效性

                                if((bitPos<0)||(bitPos>=numButs))

                                               throw new IndexoutofRangeException();

                               //返回指定索引的位的状态

                                         return (byteArray[bitPos/8]&(1<<(bitPos %8]))!=0;

                                   }

                              //下面是索引器的set访问器方法

                             set{

                                   if((bitPos<0)||(bitPos>=numBits))

                                                throw new IndexOutRangeException();

 

                              

你可能感兴趣的:(框架,C#,Class,byte)