C#.NET 索引器

自定义索引器,一般用于自定义集合类中并用来取得集合实例中的某一个元素。

而且C#.NET 有泛型集合可以使用。写这本文章主要是回顾一些容易遗忘的东西。

namespace AspxDemo_Lib
{
    
public class ProductCollection : CollectionBase
    {
        
public Product this[int index]
        {
            
set { base.InnerList[index] = value; }
            
get { return (Product)base.InnerList[index]; }
        }
        
public void Add(Product product)
        {
            
base.InnerList.Add(product);
        }
    }

    
public class Product
    {
        
public string Name { getset; }
        
public string Site { getset; }
    }
}

 

下面是在单元测试中 使用刚建的索引器:

 

 [TestMethod]
        
public void 索引器单元测试()
        {
            ProductCollection protites 
= new ProductCollection();
            protites.Add(
new Product { Name = "A", Site = "001" });
            protites.Add(
new Product { Name = "B", Site = "002" });

            Product expected 
= null;
            Product actual 
= protites[0];
            Assert.AreEqual(expected, actual);
        }

 

 

posted @ 2011-05-18 15:52  yoolo wu  阅读(478)  评论(0编辑  收藏  举报