今天写了两个类和一个用户控件:ListBase 基类,SPCacheFactory 缓存变量类,SmoothLeftMenu用户控件。
实现了这样的操作:SPCacheFactory定义了一个函数GetMenuCahceData():从数据库中获取信息放入缓存变量;在ListBase 的构造函数中调用SPCacheFactory.GetMenuCahceData();在用户控件中定义了一个变量获取缓存信息:
DataTable DtMenu=SPCacheFactory.GetCahceData(SPCacheFactory.MenuCacheKey) as DataTable;
protected void Page_Load(object sender, EventArgs e)
{
string currentid = GetIDbyUrl();
string lev1ID = GetRootNodeOfCurrentWeb(currentid);
if (!lev1ID.Equals("0"))
{
string menuContent = BuidMenuContent(lev1ID, 2);
this.ltlLeftMenu.Text = menuContent;
}
}
正常情况下应该是先执行ListBase 中的构造函数,调用缓存类中的GetMenuCahceData()函数,再在用户控件中对DtMenu进行实例化,可是今天试了几次,总是报错“未将对象引用至实例”,用户控件中的DtMenu显示为null。
调试之后发现了执行顺序,先执行用户控件中的变量实例化,再试下基类的构造函数,所以报错。
将变量修改为属性之后运行正常。
protected void Page_Load(object sender, EventArgs e)
{
string currentid = GetIDbyUrl();
string lev1ID = GetRootNodeOfCurrentWeb(currentid);
if (!lev1ID.Equals("0"))
{
string menuContent = BuidMenuContent(lev1ID, 2);
this.ltlLeftMenu.Text = menuContent;
}
}
DataTable tempDtMenu;
private DataTable DtMenu
{
get
{
if (tempDtMenu == null)
tempDtMenu = SPCacheFactory.GetCahceData(SPCacheFactory.MenuCacheKey) as DataTable;
return tempDtMenu;
}
}