一个强类型ArrayList类。

本文介绍了一个自定义的StringBase类,该类继承自CollectionBase,并实现了字符串集合的基本操作,如添加、插入、删除等。此外,为了确保集合中只包含字符串类型的数据,还实现了类型检查以防止插入非字符串类型的值。

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

class StringBase : CollectionBase
    
{
        
public string this[int index]
        
{
            
get return ((string)List[index]); }
            
set { List[index] = value; }
        }

        
public int Add(string value)
        
{
            
return (List.Add(value));
        }

        
public int IndexOf(string value)
        
{
            
return (List.IndexOf(value));
        }

        
public void Insert(int index, string value)
        
{
            List.Insert(index, value);
        }

        
public void Remove(string value)
        
{
            List.Remove(value);
        }

        
public bool Contains(string value)
        
{
            
return (List.Contains(value));
        }

        
protected override void OnInsert(int index, object value)
        
{
            
if (value.GetType() != Type.GetType("System.String"))
                
throw new ArgumentException("value must be of type string.""value");
            
base.OnInsert(index, value);
        }

        
protected override void OnRemove(int index, object value)
        
{
            
if (value.GetType() != Type.GetType("System.String"))
                
throw new ArgumentException("value must be of type string.""value");
            
base.OnRemove(index, value);
        }

        
protected override void OnSet(int index, object oldValue, object newValue)
        
{
            
if (newValue.GetType() != Type.GetType("System.String"))
                
throw new ArgumentException("newValue must be of type string.""newValue");
            
base.OnSet(index, oldValue, newValue);
        }

        
protected override void OnValidate(object value)
        
{
            
if (value.GetType() != Type.GetType("System.String"))
                
throw new ArgumentException("value must be of type string.");
            
base.OnValidate(value);
        }

    }
 避免在增加不同类型数据时出错。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值