假设出于某种原因我想创建一个派生自 Control 而不是 WebControl 的自定义控件。我们还假设我需要处理属性(即实现 IAttributeAccessor),并且我想像 WebControl 一样通过使用 AttributeCollection 来实现。
WebControl 像这样实现 Attributes 属性:
public AttributeCollection Attributes
{
get
{
if (this.attrColl == null)
{
if (this.attrState == null)
{
this.attrState = new StateBag(true);
if (base.IsTrackingViewState])
{
this.attrState.TrackViewState();
}
}
this.attrColl = new AttributeCollection(this.attrState);
}
return this.attrColl;
}
}
注意以下几点:
- 如果不提供 StateBag,则无法创建 AttributeCollection。
- 我们必须创建一个新的 StateBag。重用控件的 StateBag 是不明智的,因为属性的名称可能作为控件存储的值。
- 我们不能在 StateBag 上调用 TrackViewState,因为这是一个内部方法。
- StateBag 是一个密封类。
据我了解,如果我想使用 AttributeCollection,我必须使用一个新的 StateBag,它永远(不诉诸反射等技巧)实际上无法正确管理状态。
我错过了什么吗?
最佳答案
要在自定义 StateBag 上调用 TrackViewState,您必须将其转换为它的接口(interface)。
StateBag mybag = new StateBag();
(mybag as IStateManager).TrackViewState();
我猜这个设计决定是为了向消费者隐藏 ViewState 的实现。有一些关于在 documentation page for IStateManager 上实现自定义状态跟踪的信息。 .
关于c# - ASP.NET StateBag 和自定义控件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1160442/