我有一个用PartialCaching属性声明的控件,如下所示:
[PartialCaching(60 * 60 * 12)]
public class MyControl : Control {
// control contents ...
}
但是我使用new关键字在代码中创建它。问题是如果控件在缓存中,我下次不能再次创建控件,但我需要将控件添加到页面层次结构中,否则不会呈现任何内容。我在伪代码中需要的是这样的:
if (myControlIsCached) {
var ctl = ???; // something that represents the cached control
// e.g. could be: new LiteralControl( myControlCachedData )
this.Controls.Add( ctl );
}
else {
var ctl = new MyControl();
// setup control ...
this.Controls.Add( ctl );
}
这样做的正确方法是什么?
谢谢大家。
答案 0 :(得分:1)
我相信你正在寻找这样的事情:
Control possiblyCachedControl = LoadControl("path to control");
MyControlType control = null;
if (possiblyCachedControl is MyControlType)
{
//control wasn't cached
control = possiblyCachedControl as MyControlType;
}
else if (possiblyCachedControl is PartialCachingControl && ((PartialCachingControl)possiblyCachedControl).CachedControl != null)
{
//control was cached
control = (MyControlType)((PartialCachingControl)possiblyCachedControl).CachedControl;
}
if (control != null)
{
//use the control
}