关于ArrayList

最近的程序中需要用到动态数组,所以使用ArrayList。
在使用过程中出现了一些问题,这里记录一下。
1、在删除一个内容后ArrayList会发生中断?
          public   void  DeleteOneUser( string  userSIPURI)
         
{
               
foreach (PoCContactItem pocContactItem in userArray)
               
{
                    
if (pocContactItem.GetUserSipUri() == userSIPURI)
                    
{
                        DecresUserArray(pocContactItem);
                    }

                }

                RefeshSesonTreVw();
          }
上面的代码目的是:在一个userArray(ArrayList)中根据一个用户的SIPURI来定位一个具体的项。使用了foreach循环,发现SIPURI相等的项后直接将该项删掉。最后刷新一下整个会话中的用户树结构。
但是这样会出现问题:userArray中的欲删项可以删掉,但是在继续foreach循环时程序会抛一个" InvalidOperationException"的异常。
在msdn上查了一下,该异常说明如下:When you run your code in the Visual Studio debugger, an InvalidOperationException is thrown if you access a UI element from any thread other than the one on which it was created. The debugger does this to alert you to a dangerous programming practice. UI elements are not thread-safe and should be accessed only on the thread that created them. 说是如果如果不是在创建该UI element的线程、而是在另外一个线程中删除这个UI element的话,会抛这个异常。可是我这之前我并没有创建新的线程,所以问题应该不是这个,继续排查。
我突然想到,由于这是一个foreach循环,会不会是删除了ArrayList某一项后导致了foreach的中断?所以我修改了代码:
          public   void  DeleteOneUser( string  userSIPURI)
         
{
               
foreach (PoCContactItem pocContactItem in userArray)
               
{
                    
if (pocContactItem.GetUserSipUri() == userSIPURI)
                    
{
                        DecresUserArray(pocContactItem);
                        RefeshSesonTreVw();
                        
return;
                    }

                }

          }

在调用删除该项的DecresUserArray函数后,return,直接跳出函数(因为没有类似break的语句可以只跳出foreach循环,所以这里只好用return跳出整个函数),问题解决。
其实一开始是用的下面方法:其实也只是将删除该项的DecresUserArray函数挪到了foreach循环的外面,和上面的方法殊途同归。
         public   void  DeleteOneUser( string  userSIPURI)
        
{
            
bool toDel = false;
            PoCContactItem userToDel 
= new PoCContactItem();
            
foreach (PoCContactItem pocContactItem in userArray)
            
{
                
if (pocContactItem.GetUserSipUri() == userSIPURI)
                
{
                    
//DecresUserArray(pocContactItem);
                    userToDel = pocContactItem;
                    toDel 
= true;
                }

            }

            
if (toDel)
            
{
                DecresUserArray(userToDel);
                RefeshSesonTreVw();
            }

        }

这里猜测尽管ArrayList是动态的,但在foreach循环删除ArrayList某项后会导致ArrayList内容断链,所以不能在ArrayList中使用Remove方法。
也不知道猜测的对不。。。
 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值