索引器(indexer)是一種特殊的類方法 ,允許使用一個看起來像獲取數組元素一樣的方法來訪問類的內部數據 。下面使用BitList類來演示 indexer的簡單用法 。
在BitList類中 ,索引器返回 number 域 第 i 個比特位(bit)的值 。
public class BitList { private BitList() { } private static BitList instance; //獲取單實例 public static BitList GetInstance() { if (instance == null) { instance = new BitList(); } return instance; } private int number = 0; public int Number { get { return number; } set { number = value; } } //一個所索引器 //返回一個比特位的值 public int this[int index] { get { int val = Number >> index; return val & 1; } } }
設計一個簡單的窗體 :
TextBox txtNumber;//用來輸入number
NumbericUpDown numUD;//獲取index
ListBox lsBits;//顯示number 域 第 index 個比特位的值
public partial class FrmBitList : Form
{
public FrmBitList()
{
InitializeComponent();
}
private void numUD_ValueChanged(object sender, EventArgs e)
{
if (this.txtNumber.Text.Length < 1)
{
return;
}
//從調節鈕控件中獲取索引值
int index =(int)this.numUD.Value;
if (index == -1)
{
return;
}
//通過BitList的索引器獲取bit值
int bit = BitList.GetInstance()[index];
lsBits.Items.Add(bit.ToString());
}
private void txtNumber_KeyPress(object sender, KeyPressEventArgs e)
{
//設置KeyPress事件已經處理過
e.Handled = true;
//只能輸入數字 和 BackSpace
if (e.KeyChar >= '0' && e.KeyChar <= '9' || e.KeyChar == '\b')
{
e.Handled = false;
}
}
private void txtNumber_TextChanged(object sender, EventArgs e)
{
//更新BitList中的屬性Number
if (txtNumber.Text.Length < 1)
{
BitList.GetInstance().Number = 0;
}
else
{
BitList.GetInstance().Number = Convert.ToInt32(txtNumber .Text);
}
this.numUD.Value = -1;//復位
this.lsBits.Items.Clear();//清空
}
}
運行效果: