在Web开发中,经常需要使用Session来保存特定用户的信息,在我们的程序中很多地方散落着类似下面的语句:
int
userAge
=
(
int
)
this
.Session[
"
UserAge
"
];
我们知道,Session中存放的是键值对,键是string类型的,如果我们一不小心把上面的语句写成这样:
int
userAge
=
(
int
)
this
.Session[
"
UseAge
"
];
编译期不会发现这个错误,但运行时一定会抛出异常,这是在程序中直接操作Session可能引发的问题之一。另外,每次获取userAge的时候都要写代码进行强制转换,感觉很繁琐。我们需要一个解决方案来解决这些问题。我的做法是引入一个Session的包装,使之对象化、强类型化。就像接下来的例子一样:
public
class
SessionHelper
{
private HttpSessionState curSession;
public SessionHelper(HttpSessionState session)
{
this .curSession = session;
}
public static SessionHelper CreateInstance(HttpSessionState session)
{
return new SessionHelper(session);
}
public string UserID
{
get
{
return this .curSession[ " UserID " ].ToString();
}
set
{
this .curSession[ " UserID " ] = value ;
}
}
public int UserAge
{
get
{
return ( int ) this .curSession[ " UserAge " ];
}
set
{
this .curSession[ " UserAge " ] = value ;
}
}
// 某用户上传的所有图片
public ArrayList PicList
{
get
{
if ( this .curSession[ " PicList " ] == null )
{
this .curSession[ " PicList " ] = new ArrayList();
}
return (ArraayList) this .curSession[ " PicList " ];
}
}
// 清空图片列表
public void ClearAllPics()
{
this .PicList.Clear();
}
}
{
private HttpSessionState curSession;
public SessionHelper(HttpSessionState session)
{
this .curSession = session;
}
public static SessionHelper CreateInstance(HttpSessionState session)
{
return new SessionHelper(session);
}
public string UserID
{
get
{
return this .curSession[ " UserID " ].ToString();
}
set
{
this .curSession[ " UserID " ] = value ;
}
}
public int UserAge
{
get
{
return ( int ) this .curSession[ " UserAge " ];
}
set
{
this .curSession[ " UserAge " ] = value ;
}
}
// 某用户上传的所有图片
public ArrayList PicList
{
get
{
if ( this .curSession[ " PicList " ] == null )
{
this .curSession[ " PicList " ] = new ArrayList();
}
return (ArraayList) this .curSession[ " PicList " ];
}
}
// 清空图片列表
public void ClearAllPics()
{
this .PicList.Clear();
}
}
这样,我们用起来就非常方便了:
SessionHelper sessionHelper
=
SessionHelper.CreateInstance(
this
.Session);
ArrayList picList = sessionHelper.PicList;
// 处理picList中的图片
sessionHelper.ClearAllPics();
ArrayList picList = sessionHelper.PicList;
// 处理picList中的图片
sessionHelper.ClearAllPics();
引入这一层包装,可以使我们的程序的可读性、可维护性更好,而且将原来的一些运行期的错误提前到了编译期,这也是强类型带来的好处。