在我们做asp.net网站的时候 经常会判断一个值是不是为空 比如session是否为空 或者是cookies是否为空 如果为空的时候 你就已经引用了 那么就会报错
错误信息为 未将对象引用设置到对象的实例 那么这2个的判断也是不一样的
错误的例子
1
if
(
!
string
.IsNullOrEmpty(Request.QueryString[
"
userid
"
].ToString()))
2 {
3 DoSomeThing();
4 }
5
2 {
3 DoSomeThing();
4 }
5
在这里 如果我们想判断获得的userid是否为空 首先应该是判断这个对象是否为空 所以正确的应该是
1
protected
void
Page_Load(
object
sender, EventArgs e)
2 {
3 if ( string .IsNullOrEmpty(Request.QueryString[ " userid " ])) // 这里是判断对象是否为空 所以不必加tostring
4
5 {
6 Response.Write( " 空 " );
7 }
8
9 }
2 {
3 if ( string .IsNullOrEmpty(Request.QueryString[ " userid " ])) // 这里是判断对象是否为空 所以不必加tostring
4
5 {
6 Response.Write( " 空 " );
7 }
8
9 }
那么假如是判断Cookies呢? 还是用string.IsNullOrEmpty来判断么?错了 这个是用来判断string类型的 而cookies直接判断是否为空就可以了
下面为正解
1
if
(Request.Cookies[
"
joey
"
]
==
null
)
2 {
3 Response.Write( " 空 " );
4 }
2 {
3 Response.Write( " 空 " );
4 }