日期:2014-05-17  浏览次数:20558 次

foreash Hashtable改变值问题
Hashtable ht = (Hashtable)Session["c"];
Hashtable ht2 = ht;

foreach (System.Collections.DictionaryEntry item in ht)
{
  M_OfProduct m_OfProduct = item.Value as M_OfProduct; //M_OfProduct 是个Model层
  
  m_OfProduct.ProductCount=3; //改变数量-----

  ht2["ca"] = m_OfProduct; //存入Hashtable()
}

Session["c"] = ht2;
----------------------------
执行后提示错误:集合已修改;可能无法执行枚举操作。
这里用两个Hashtable就是因为Hashtable的值改变后还在遍历才会报这种错误,。
 后来经测试还是一样的错误,它们应该是引用类型,。
----------
 在网上查询说是只能用for才行,。
知道的说下用foreach 的话,还有什么方法,
 如果用for来循环,麻烦贴下代码。,对Hashtable不大熟...

------解决方案--------------------
for (int i=0;ht.Items.Count;i++)
{
System.Collections.DictionaryEntry item =ht.Items[i];
}
------解决方案--------------------
foreach (System.Collections.DictionaryEntry item in ht)
中不能更改集合的值,
其实这个原因可以想得到的:因为你又在遍历集合,又在改变集合,你叫运行库如何识别啊。
举个例子:公司要盘点了,一般都是要放假盘点的,为啥呢?放假后库存都是静止状态的,才能盘点撒。
如果你在盘点时,有改懂库存,你咋个盘点呢?
------解决方案--------------------
每个实现的迭代器,返回类型必须为 IEnumerable、IEnumerator、IEnumerable<T> 或 IEnumerator<T>。foreach中的迭代变量是即为IEnumerable、IEnumerator、IEnumerable<T> 或 IEnumerator<T>类型。从上面的接口可以看出,object Current是只读的,因此,foreach迭代变量只能是只读的。
C# code

namespace System.Collections  
{  
    // 摘要:  
    //     支持对非泛型集合的简单迭代。  
    [ComVisible(true)]  
    [Guid("496B0ABF-CDEE-11d3-88E8-00902754C43A")]  
    public interface IEnumerator  
    {  
        // 摘要:  
        //     获取集合中的当前元素。  
       //  
        // 返回结果:  
        //     集合中的当前元素。  
        //  
        // 异常:   
       //   System.InvalidOperationException:  
        //     枚举数定位在该集合的第一个元素之前或最后一个元素之后。  
        object Current { get; }  
        bool MoveNext();  
        void Reset();  
    }  
}  
  
namespace System.Collections  
{  
    // 摘要:  
    //     公开枚举数,该枚举数支持在非泛型集合上进行简单迭代。  
    [ComVisible(true)]  
    [Guid("496B0ABE-CDEE-11d3-88E8-00902754C43A")]  
    public interface IEnumerable  
    {  
        // 摘要:  
        //     返回一个循环访问集合的枚举数。  
        //  
        // 返回结果:  
        //     可用于循环访问集合的 System.Collections.IEnumerator 对象。  
       [DispId(-4)]  
        IEnumerator GetEnumerator();  
    }  
}

------解决方案--------------------
探讨

每个实现的迭代器,返回类型必须为 IEnumerable、IEnumerator、IEnumerable<T> 或 IEnumerator<T>。foreach中的迭代变量是即为IEnumerable、IEnumerator、IEnumerable<T> 或 IEnumerator<T>类型。从上面的接口可以看出,object Current是只读的,因此,foreach迭代变量只能是只读的。
……