Chinaunix首页 | 论坛 | 博客
  • 博客访问: 578168
  • 博文数量: 752
  • 博客积分: 40000
  • 博客等级: 大将
  • 技术积分: 5005
  • 用 户 组: 普通用户
  • 注册时间: 2008-10-13 14:47
文章分类

全部博文(752)

文章存档

2011年(1)

2008年(751)

我的朋友

分类:

2008-10-13 16:42:55

Abstracting Data Fields
class Employee {
   private String Name;  // field is now private
   private Int32 Age;    // field is now private

   public String GetName() {
      return(Name);
   }

   public void SetName(String value) {
      Name = value;
   }

   public Int32 GetAge() {
      return(Age);
   }

   public void SetAge(Int32 value) {
      if (value <= 0)
         throw(new ArgumentException("Age must be greater than 0");
      Age = value;
   }
}

Using Get and Set Properties
class Employee {
   private String _Name; // prepended '_' to avoid conflict
   private Int32 _Age;   // prepended '_' to avoid conflict

   public String Name {
      get { return(_Name); }
      set { _Name = value; } // 'value' always identifies the new value
   }

   public Int32 Age {
      get { return(_Age); }
      set {
         if (value <= 0)    // 'value' always identifies the new value
            throw(new ArgumentException("Age must be greater than 0");
         _Age = value;
      }
   }
}

Using Index Properties
class BitArray {
    private Byte[] byteArray;
    public BitArray(int numBits) {
        if (numBits <= 0)
            throw new ArgumentException("numBits must be > 0");
        byteArray = new Byte[(numBits + 7) / 8];
    }

    public Boolean this[Int32 bitPosition] {
        get {
            if ((bitPosition < 0) ||
             (bitPosition > byteArray.Length * 8 - 1))
                throw new IndexOutOfRangeException();
            return((byteArray[bitPosition / 8] &
                   (1 << (bitPosition % 8))) != 0);
        }
        set {
            if ((bitPosition < 0) ||
             (bitPosition > byteArray.Length * 8 - 1))
                throw new IndexOutOfRangeException();
            if (value) {
                byteArray[bitPosition / 8] = (Byte)
                   (byteArray[bitPosition / 8] |
                   (1 << (bitPosition % 8)));
            } else {
                byteArray[bitPosition / 8] = (Byte)
                   (byteArray[bitPosition / 8] &
                   ~(1 << (bitPosition % 8)));
            }
        }
    }
}


--------------------next---------------------

阅读(314) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~