用索引器简化的C#类型信息访问

本文介绍了C#中的索引器(Indexer)概念及其使用方法,通过实例展示了如何定义和使用索引器来访问集合中的元素,并提供了单元测试示例。

“C#中的Indexer给人一种更’透彻’的感觉,集合类型就是集合类型,有自己专用但又最简洁的访问方式,而且同一类型可以有不同的索引访问方式。”

   --《设计模式_基于C#的工程化实现及扩展》

示例代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace BangWorks.PractcalPattern.Concept.Inder
{
    public class SingleColumnCollection
    {
        //实现一个字符串数组,以便用索引器访问
        string[] Names = new string[] { "BangChen", "BangJiang", "Data" };

        //实现数字索引器
        public string this[int index]
        {
            get { return Names[index]; }
        }
        //实现字符串索引器
        public string[] this[string strIndex]
        {
            get
            {
                if ((Names == null) || (Names.Length <= 0)) return null;
                return Array.FindAll<string>(Names, delegate(string cadicate)
                {return cadicate.StartsWith(strIndex);});
            }

        }
    }
}

单元测试

/// <summary>
        ///Item 的测试
        ///</summary>
        [TestMethod()]
        public void ItemTest()
        {
            SingleColumnCollection target = new SingleColumnCollection(); // TODO: 初始化为适当的值
            int index = 0; // TODO: 初始化为适当的值
            string actual;
            actual = target[index];
            Assert.AreEqual( "BangChen",actual);
        }

        /// <summary>
        ///Item 的测试
        ///</summary>
        [TestMethod()]
        public void ItemTest1()
        {
            SingleColumnCollection target = new SingleColumnCollection(); // TODO: 初始化为适当的值
            string strIndex = "Bang"; // TODO: 初始化为适当的值
            string[] actual;
            actual = target[strIndex];
            Assert.AreEqual<int>(2,actual.Length);
        }

小提示
在Vs中,输入indexer,再键入Tab键,可以利用vs自带indexer模板,创建自己的索引。

转载于:https://www.cnblogs.com/kissazi2/archive/2013/03/17/2964075.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值