索引器(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();//清空
}
}
运行效果: