CSharp中索引器的简单使用

本文介绍了一种特殊的方法——索引器(indexer),它允许以类似数组的方式访问类的内部数据。通过一个名为BitList的类展示了索引器的基本用法,包括如何创建索引器以及如何在类中使用它来获取特定位置的比特位值。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

    }
复制代码


   运行效果:

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值