日期:2014-05-19  浏览次数:20865 次

测试一个封装字段,出现索引超出范围
private   void   Page_Load(object   sender,   System.EventArgs   e)
{
//   在此处放置用户代码以初始化页面
this.Add();
Response.Write   (this.alFieldItems.Count);
}
protected   System.Collections.ArrayList   alFieldItems   =   new   System.Collections.ArrayList(10);   //   10对值

public   void   AddFieldItem(string   _fieldName,object   _fieldValue)     //   object,因为值类型不确定!
{
for(int   i=0;i <alFieldItems.Count;i++)
{
if(((DbKeyItem)this.alFieldItems[i]).fieldName   ==   _fieldName)
{
throw   new   ArgumentException( "The   field   name   has   existed! ");
}
this.alFieldItems.Add(new   DbKeyItem(_fieldName,_fieldValue));
Response.Write   (this.alFieldItems.Count);
}
}
public   void   Add()
{
this.AddFieldItem( "userName ", "xlingfeng ");
}

public   class   DbKeyItem
{
///   <summary>
///     字段名称
///   </summary>
public   string   fieldName;
///   <summary>
///     字段值
///   </summary>
public   string   fieldValue;
///   <summary>
///     类的构造函数
///     <para   name= "_fieldName "> 字段名称。 </para>
///     <para   name= "_fieldValue "> 字段值。 </para>
///   </summary>
public   DbKeyItem(string   _fieldName,object   _fieldValue)
{
this.fieldName   =   _fieldName;
this.fieldValue   =   _fieldValue.ToString();
}
}


----------预期实现效果
  将   字段和字段值放入   数组中待以后处理

  为何   Count的值认为   0   呢??

------解决方案--------------------
你把this.alFieldItems.Add(new DbKeyItem(_fieldName,_fieldValue));放在了for循环里当然不会添加值进去,因为永远都进不去这个循环
------解决方案--------------------

public void AddFieldItem(string _fieldName,object _fieldValue) // object,因为值类型不确定!
{
bool isFieldExisted = false;
for(int i=0;i <alFieldItems.Count;i++)
{
if(((DbKeyItem)this.alFieldItems[i]).fieldName == _fieldName)
{
throw new ArgumentException( "The field name has existed! ");
isFieldExisted = true;
break;
}
}

if(isFieldExisted == false)
{
this.alFieldItems.Add(new DbKeyItem(_fieldName,_fieldValue));
}

Response.Write (this.alFieldItems.Count);
}