通用状态集合






2.75/5 (4投票s)
用于 ASP.NET 状态集合的 IStateManager 的通用实现。
下载 StateCollection.zip - 925 字节
引言
在构建自定义 ASP.NET 控件时,我经常需要为对象集合实现 IStateManager,以便将它们持久化到 ViewState 中。
通常的做法是继承 List<T> 并实现 IStateManager 来创建集合。
在大多数情况下,代码都是相同的,我只需要更改列表的泛型类型。
这就是为什么它成为通用实现的一个理想候选者。这种实现使得
通用状态集合使我能够在无需编写任何额外代码的情况下使用任何类型的状态集合。
代码
StateCollection
继承自 List<T>
类并实现了 IStateManager。请注意,我要求 StateCollection
的泛型类型本身也实现 IStateManager。
以下是 StateCollection 类的源代码
/// <summary>
///
/// </summary>
/// <typeparam name="T"></typeparam>
public class StateCollection<T> : List<T>, IStateManager where T : IStateManager, new(){
#region Fields /////////////////////////////////////////////////////////////////
bool _tracking;
#endregion
#region Properties /////////////////////////////////////////////////////////////
/// <summary>
/// When implemented by a class, gets a value indicating whether a server control is tracking its view state changes.
/// </summary>
/// <value></value>
/// <returns>true if a server control is tracking its view state changes; otherwise, false.</returns>
public bool IsTrackingViewState {
get { return _tracking; }
}
#endregion
#region Methods /////////////////////////////////////////////////////////////////
/// <summary>
/// Loads the state of the view.
/// </summary>
/// <param name="savedState">State of the saved.</param>
public void LoadViewState(object savedState) {
object[] state = savedState as object[];
if (state != null) {
T item;
bool exists;
for (int i = 0; i < state.Length; i++) {
item = (exists =( i < this.Count)) ? this[i] : new T();
item.LoadViewState(state[i]);
if (this.IsTrackingViewState)
item.TrackViewState();
if(!exists) Add(item);
}
}
}
/// <summary>
/// When implemented by a class, saves the changes to a server control's view state to an <see cref="T:System.Object"/>.
/// </summary>
/// <returns>
/// The <see cref="T:System.Object"/> that contains the view state changes.
/// </returns>
public object SaveViewState() {
if (this.Count > 0) {
int count = this.Count;
object[] state = new object[count];
for (int i = 0; i < count; i++) {
state[i] = this[i].SaveViewState();
}
return state;
}
else
return null;
}
/// <summary>
/// When implemented by a class, instructs the server control to track changes to its view state.
/// </summary>
public void TrackViewState() {
_tracking = true;
}
#endregion
}
关注点
有关如何使用 StateCollection
的示例,您可以参考 GoogleMap 控件 的源代码。
历史
- 2008年3月22日 - 初始发布