您的位置:首页 > 编程语言 > C#

CSharp中索引器的简单使用

2014-01-01 09:33 1001 查看
索引器(indexer)是一种特殊的类方法 ,允许使用一个看起来像获取数组元素一样的方法来访问类的内部数据 。下面使用BitList类来演示 indexer的简单用法 。
  在BitList类中 ,索引器返回 number 域 第 i 个比特位(bit)的值 。

  设计一个简单的窗体 :

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();//清空
}

}


  运行效果:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: