c#中自定义类索引器

本文介绍两种实现Product集合类的方法:一种是从CollectionBase继承并使用数字作为索引;另一种是从DictionaryBase继承并使用字符串作为索引。每种方法都提供了添加、删除及索引器重载函数。

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

1.采用从CollectionBase抽象基类继承的方式实现Product集合类:
           以数字做为索引值,详细成员查看msdn,还有更多的重载函数
 1 using System;
 2 using System.Collections;    
 3 public class productCollection:CollectionBase     
 4 {
 5     public void Add(product newProduct)//添加类对象重载函数         
 6     {              
 7         List.Add(newProduct);         
 8     }         
 9     public void Remove(product oldProduct)//移除类对象重载函数 
10     {              
11         List.Remove(oldProduct);         
12     }         
13     public product this[int productIndex]//索引器重载函数
14     {              
15         get{                   
16             return (product)List[productIndex];              
17         }              
18         set{                   
19             List[productIndex]=value;              
20         }         
21     }     
22 }


2.采用从DictionaryBase抽象基类继承的方式实现Product集合类:
         以字符串做为索引值,详细成员查看msdn,还有更多的重载函数

 1 using System;
 2 using System.Collections; 
 3 public class ShortStringDictionary : DictionaryBase  {      
 4     public String this[ String key ]  //索引器重载函数     
 5     {         
 6         get{              
 7             return( (String) Dictionary[key] );         
 8         }         
 9         set{              
10             Dictionary[key] = value;         
11         }     
12     }       
13     public void Add( String key, String value )  //添加类对象重载函数     
14     {         
15         Dictionary.Add( key, value );     
16     }       
17     public void Remove( String key )  //移除类对象重载函数     
18     {         
19         Dictionary.Remove( key );     
20     }     
21 


 

转载于:https://www.cnblogs.com/FireYang/archive/2006/07/22/457253.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值