C#.NET 索引器

it2022-06-27  82

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

而且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 {  get set ; }         public   string  Site {  get set ; }    }}

 

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

 

 [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);        }

 

 

转载于:https://www.cnblogs.com/yoolonet/archive/2011/05/18/2050183.html


最新回复(0)