解决方法
DanHerbert得到了它. Darn,我也花了几个小时!在尝试回答这个问题的过程中,我提出了一个简化的通用StateManagedCollection,它继承自框架的内置StateManagedCollection,基于版本
here.也许你会发现它很有用.我的示例项目的完整源代码可用于
here.
using System; using System.Collections; using System.Collections.Specialized; using System.Security.Permissions; using System.Web; using System.Collections.Generic; using System.Web.UI; namespace Web { public abstract class StateManagedCollection<T> : StateManagedCollection,IList<T>,ICollection<T>,IEnumerable<T> where T : class,IStateManagedItem,new() { protected override object CreateKnownType(int index) { return Activator.CreateInstance<T>(); } protected override Type[] GetKnownTypes() { return new Type[] { typeof(T) }; } protected override void SetDirtyObject(object o) { ((IStateManagedItem)o).SetDirty(); } #region IList<T> Members public int IndexOf(T item) { return ((IList)this).IndexOf(item); } public void Insert(int index,T item) { ((IList)this).Insert(index,item); if (((IStateManager)this).IsTrackingViewState) { this.SetDirty(); } } public void RemoveAt(int index) { ((IList)this).RemoveAt(index); if (((IStateManager)this).IsTrackingViewState) { this.SetDirty(); } } public T this[int index] { get { return (T)this[index]; } set { this[index] = value; } } #endregion #region ICollection<T> Members public void Add(T item) { ((IList)this).Add(item); this.SetDirty(); } public bool Contains(T item) { return ((IList)this).Contains(item); } public void CopyTo(T[] array,int arrayIndex) { ((IList)this).CopyTo(array,arrayIndex); } public bool IsReadOnly { get { return false; } } public bool Remove(T item) { if (((IList)this).Contains(item)) { ((IList)this).Remove(item); return true; } return false; } #endregion #region IEnumerable<T> Members IEnumerator<T> IEnumerable<T>.GetEnumerator() { throw new NotImplementedException(); } #endregion #region IEnumerable Members IEnumerator IEnumerable.GetEnumerator() { return ((IList)this).GetEnumerator(); } #endregion } }