C#基础 结构、枚举、表达式、运算符
2011-07-12 15:39
609 查看
<iframe align="center" marginwidth="0" marginheight="0" src="http://www.zealware.com/csdnblog336280.html" frameborder="0" width="336" scrolling="no" height="280"></iframe> CodeProject的这篇文章确实对我有所启迪,
http://www.codeproject.com/useritems/SessionWrapper.asp#xx1208856xx。
诚如作者所说,我们经常在ASP.NET用许多类似于下面的代码来检测Session中存储的对象,来防止Session过期后存储的变量丢失问题:
Int32 nUserID = -1;
if ( null != Session["userID"] ) {
if ( Session["userID"] is Int32 ) {
if ( 0 nUserID = (Int32) Session["userID"]
}
}
}
if ( -1 == nUserID )
{
throw new ApplicationException ( "Unexpected situation: userID invalid." );
}
this.doSomething( nUserID );
这样的代码会遍布各处。
那么,利用他的这个封装方案来做重构,确实让代码简洁干净了不少!
经过他的封装,上面的代码用这么一句话就行了:
this.doSomething( CCurrentSession.UserID )
他的类其实也很简单,如下所示:
usingSystem;
usingSystem.Web;
/**////--------------------------------------------------------------------
///DevelopedbyM.vanEijkel-aug2005
///[e]:marcelvaneijkel@gmail.com
///[w]:www.vaneijkel.com
namespaceVanEijkel.Web
{
/**////<summary></summary>
///Wrapperclassforthesessionobject.
///Itcentralizesthelogicforretrievingandvalidationofsessioninformation.
///Byusinganapproachlikethisyouimprovetheprotectionandencapsulationofexistingcode.
///Itoffersasimple,low-risk,easymanageablewaytoimproveexistingWebApplication.
///Therfore,IcallitwebRefactoring.
///
publicclassCurrentSession
{
Constants#regionConstants
privateconstStringsMANDATORY_SESSION_KEY_NOT_FOUND_MSG="Sessionvariableexceptedbutdoesnotexist.Key={0}";
privateconstStringsMANDATORY_SESSION_VALUE_INVALID_NULL="Nonenullsessionvalueexcepted.Key={0}";
privateconstInt32nUSERID_UNKOWN=-1;
privateconstInt32nUSERID_MINIMUM=1;
privateconstStringsUSERID_INVALID="InvalidUserID:{0}.UserIDshouldbelargerthan:{1}";
#endregion
UserID#regionUserID
/**////<summary></summary>
///ReturnstheuserIDasaInt32insteadofanobject.
///Thiswayyouwillgetthecompilerprotectionandintelligencesupportyouneed.
///
publicstaticInt32UserID
{
get
{
return(Int32)GetValueOrDefault(eKeys.UserID,nUSERID_UNKOWN);
}
set
{
if(nUSERID_MINIMUM>=value)
{
thrownewApplicationException(String.Format(sUSERID_INVALID,value,nUSERID_MINIMUM));
}
SetValue(eKeys.UserID,value);
}
}
#endregion
private:GetValueOrDefault(eKeyseKey,ObjectoDefaultValue)#regionprivate:GetValueOrDefault(eKeyseKey,ObjectoDefaultValue)
/**////<summary></summary>
///Getsthevaluefromthesessionobject.
///
///Thesessionkeytogetthevaluefor.
///Thedefaultvaluetouseifnovalidvaluestored.
///<returns></returns>Whenthevalueisnullorthekeydoesnotexist,
///thespecifieddefaultvalueisreturned.
///Otherwise,thevalueisreturned
privatestaticobjectGetValueOrDefault(eKeyseKey,ObjectoDefaultValue)
{
//getthevalue
objectoValue=GetValue(eKey);
//valuenotfoundornull?
if(null==oValue)
{
//returndefaultvalue
returnoDefaultValue;
}
//everythingoke:returnsessionvalue
returnoValue;
}
#endregion
private:GetMandatoryValue(eKeyseKey)#regionprivate:GetMandatoryValue(eKeyseKey)
/**////<summary></summary>
///Returnsthesessionvalueforasession-keythatmustexist.
///IfthekeydoesnotexistanapplicationExceptionisthrown.
///
///Thesession-keytoreturnthesession-valuefor.
///<returns></returns>Anone-nullvalue.
privatestaticobjectGetMandatoryValue(eKeyseKey)
{
//getthevalue
objectoValue=GetValue(eKey);
//keynotfoundorvaluenull?
if(null==oValue)
{
//throwapplicationExceptionbecauseitsapplicationlogicerror(noneCLR)
thrownewApplicationException(String.Format(sMANDATORY_SESSION_KEY_NOT_FOUND_MSG,eKey.ToString()));
}
//everythingoke:returnvalue
returnoValue;
}
#endregion
private:GetValue(eKeyseKey)#regionprivate:GetValue(eKeyseKey)
/**////<summary></summary>
///Getsthesessionvaluefromthespecifiedkey.
///
///Thekeytogetthevaluefrom
///<returns></returns>Thesessionvalueforthespecifiedsessionkey.
///Ifthekeydoesnotexist,nullisreturned.
///
privatestaticobjectGetValue(eKeyseKey)
{
returnHttpContext.Current.Items[eKey.ToString()];
}
#endregion
privateSetMandatoryValue(eKeyseKey,ObjectoValue)#regionprivateSetMandatoryValue(eKeyseKey,ObjectoValue)
privatestaticvoidSetMandatoryValue(eKeyseKey,ObjectoValue)
{
if(null==oValue)
{
thrownewApplicationException(String.Format(sMANDATORY_SESSION_VALUE_INVALID_NULL,eKey.ToString()));
}
}
#endregion
privateSetValue(eKeyseKey,ObjectoValue)#regionprivateSetValue(eKeyseKey,ObjectoValue)
/**////<summary></summary>
///Storesthespecifiedsession-valuetothespecifiedsession-key.
///
///Thekeyforthevaluetostoreinthesession.
///Thevaluetostoreinthesession
privatestaticvoidSetValue(eKeyseKey,ObjectoValue)
{
HttpContext.Current.Items[eKey.ToString()]=oValue;
}
#endregion
/**////<summary></summary>
///Anenumforthe
///
privateenumeKeys
{
UserID
}
}
}
http://www.codeproject.com/useritems/SessionWrapper.asp#xx1208856xx。
诚如作者所说,我们经常在ASP.NET用许多类似于下面的代码来检测Session中存储的对象,来防止Session过期后存储的变量丢失问题:
Int32 nUserID = -1;
if ( null != Session["userID"] ) {
if ( Session["userID"] is Int32 ) {
if ( 0 nUserID = (Int32) Session["userID"]
}
}
}
if ( -1 == nUserID )
{
throw new ApplicationException ( "Unexpected situation: userID invalid." );
}
this.doSomething( nUserID );
这样的代码会遍布各处。
那么,利用他的这个封装方案来做重构,确实让代码简洁干净了不少!
经过他的封装,上面的代码用这么一句话就行了:
this.doSomething( CCurrentSession.UserID )
他的类其实也很简单,如下所示:
usingSystem;
usingSystem.Web;
/**////--------------------------------------------------------------------
///DevelopedbyM.vanEijkel-aug2005
///[e]:marcelvaneijkel@gmail.com
///[w]:www.vaneijkel.com
namespaceVanEijkel.Web
{
/**////<summary></summary>
///Wrapperclassforthesessionobject.
///Itcentralizesthelogicforretrievingandvalidationofsessioninformation.
///Byusinganapproachlikethisyouimprovetheprotectionandencapsulationofexistingcode.
///Itoffersasimple,low-risk,easymanageablewaytoimproveexistingWebApplication.
///Therfore,IcallitwebRefactoring.
///
publicclassCurrentSession
{
Constants#regionConstants
privateconstStringsMANDATORY_SESSION_KEY_NOT_FOUND_MSG="Sessionvariableexceptedbutdoesnotexist.Key={0}";
privateconstStringsMANDATORY_SESSION_VALUE_INVALID_NULL="Nonenullsessionvalueexcepted.Key={0}";
privateconstInt32nUSERID_UNKOWN=-1;
privateconstInt32nUSERID_MINIMUM=1;
privateconstStringsUSERID_INVALID="InvalidUserID:{0}.UserIDshouldbelargerthan:{1}";
#endregion
UserID#regionUserID
/**////<summary></summary>
///ReturnstheuserIDasaInt32insteadofanobject.
///Thiswayyouwillgetthecompilerprotectionandintelligencesupportyouneed.
///
publicstaticInt32UserID
{
get
{
return(Int32)GetValueOrDefault(eKeys.UserID,nUSERID_UNKOWN);
}
set
{
if(nUSERID_MINIMUM>=value)
{
thrownewApplicationException(String.Format(sUSERID_INVALID,value,nUSERID_MINIMUM));
}
SetValue(eKeys.UserID,value);
}
}
#endregion
private:GetValueOrDefault(eKeyseKey,ObjectoDefaultValue)#regionprivate:GetValueOrDefault(eKeyseKey,ObjectoDefaultValue)
/**////<summary></summary>
///Getsthevaluefromthesessionobject.
///
///Thesessionkeytogetthevaluefor.
///Thedefaultvaluetouseifnovalidvaluestored.
///<returns></returns>Whenthevalueisnullorthekeydoesnotexist,
///thespecifieddefaultvalueisreturned.
///Otherwise,thevalueisreturned
privatestaticobjectGetValueOrDefault(eKeyseKey,ObjectoDefaultValue)
{
//getthevalue
objectoValue=GetValue(eKey);
//valuenotfoundornull?
if(null==oValue)
{
//returndefaultvalue
returnoDefaultValue;
}
//everythingoke:returnsessionvalue
returnoValue;
}
#endregion
private:GetMandatoryValue(eKeyseKey)#regionprivate:GetMandatoryValue(eKeyseKey)
/**////<summary></summary>
///Returnsthesessionvalueforasession-keythatmustexist.
///IfthekeydoesnotexistanapplicationExceptionisthrown.
///
///Thesession-keytoreturnthesession-valuefor.
///<returns></returns>Anone-nullvalue.
privatestaticobjectGetMandatoryValue(eKeyseKey)
{
//getthevalue
objectoValue=GetValue(eKey);
//keynotfoundorvaluenull?
if(null==oValue)
{
//throwapplicationExceptionbecauseitsapplicationlogicerror(noneCLR)
thrownewApplicationException(String.Format(sMANDATORY_SESSION_KEY_NOT_FOUND_MSG,eKey.ToString()));
}
//everythingoke:returnvalue
returnoValue;
}
#endregion
private:GetValue(eKeyseKey)#regionprivate:GetValue(eKeyseKey)
/**////<summary></summary>
///Getsthesessionvaluefromthespecifiedkey.
///
///Thekeytogetthevaluefrom
///<returns></returns>Thesessionvalueforthespecifiedsessionkey.
///Ifthekeydoesnotexist,nullisreturned.
///
privatestaticobjectGetValue(eKeyseKey)
{
returnHttpContext.Current.Items[eKey.ToString()];
}
#endregion
privateSetMandatoryValue(eKeyseKey,ObjectoValue)#regionprivateSetMandatoryValue(eKeyseKey,ObjectoValue)
privatestaticvoidSetMandatoryValue(eKeyseKey,ObjectoValue)
{
if(null==oValue)
{
thrownewApplicationException(String.Format(sMANDATORY_SESSION_VALUE_INVALID_NULL,eKey.ToString()));
}
}
#endregion
privateSetValue(eKeyseKey,ObjectoValue)#regionprivateSetValue(eKeyseKey,ObjectoValue)
/**////<summary></summary>
///Storesthespecifiedsession-valuetothespecifiedsession-key.
///
///Thekeyforthevaluetostoreinthesession.
///Thevaluetostoreinthesession
privatestaticvoidSetValue(eKeyseKey,ObjectoValue)
{
HttpContext.Current.Items[eKey.ToString()]=oValue;
}
#endregion
/**////<summary></summary>
///Anenumforthe
///
privateenumeKeys
{
UserID
}
}
}
相关文章推荐
- C#基础 结构、枚举、表达式、运算符
- 【C#基础知识】之常量、变量、枚举、字符串、转义符、运算符及表达式、try...catch等简单介绍
- 【第二篇日记】C# 的转义字符,结构定义、字符转换、类型检查、运算符以及正则表达式
- 【1】C#基础:数据类型、运算、随机、枚举、结构、数组、列表、文件和文件流、序列化、MD5
- C#基础学习笔记--数据类型,值类型,结构类型,枚举类型
- C#基础知识——运算符与表达式
- C#基础解析之Ⅱ【运算符和条件结构】
- 基础篇--03 Java运算符、表达式、分支结构
- C#基础解析之Ⅱ【运算符和条件结构】
- C,C++,C#基础一:类,结构,枚举
- 【黑马程序员】2.C#基础之常量 枚举 结构
- C#基础(四)--运算符及表达式
- C#基础篇九OOP属性结构枚举
- 用《叩响C#之门》复习C#基础知识 第三章 运算符和表达式
- C#基础精华02(静态类,值类型,引用类型,枚举,结构,ref与out)
- C#基础-结构、枚举和数组(Day4)
- C#基础精华02(静态类,值类型,引用类型,枚举,结构,ref与out)
- java基础知识-----运算符表达式和分支结构
- C#学习笔记12:枚举、结构、数组基础学习
- C#之结构、枚举和运算符