2011-08-24 4 views
20

私はそのセッションを確認したい場合は、セッションをチェックすると、このようにいくつかのこと、すなわち、nullまたは空である:時々私はチェックインの際ため空かない

if(Session["emp_num"] != null) 
{ 

    if (!string.IsNullOrEmpty(Session["emp_num"].ToString())) 
      { 
       //The code 
      } 
} 

それとも

if(Session["emp_num"] != null) 
    { 

     // The code 
    } 

with:

 if (!string.IsNullOrEmpty(Session["emp_num"].ToString())) 
       { 
        //The code 
       } 

私は以下に直面していますそれは、文字列が、他のいくつかの種類が格納されていない場合は

if (!string.IsNullOrEmpty(Session["emp_num"] as string)) 
{ 
       //The code 
} 

:セッション変数emp_numは、文字列を格納する場合は、この

null参照の例外

+2

は、この記事を見て http://stackoverflow.com/questions/234973/what-is-the-best-way-to-determine-a-session-variable-is-null -or-empty-in-c – Bobby

+0

本当にうれしい、ありがとう。 –

答えて

43

用途:例外をINGの2番目の例のように、値にアクセスする前にnullをチェックするだけです。

2

まず、セッションにSession["emp_num"]が存在するかどうかを確認してください。

あなたはそのインデクサがemp_num値を持っている場合、セッションオブジェクトを頼むか、あなたはSession["emp_num"]がそうでなければ、あなたがnull参照の例外が発生します文字列に変換しようとする前にnullではないことを確認する必要がありstring.IsNullOrEmpty(Session["emp_num"])

5

を使用することができます。

私はあなたの最初の例を考えていますが、もう少し「エレガント」にすることができます。

あり、いくつかの方法がありますが、心にバネのものがある:

if (Session["emp_num"] is string) 
{ 
} 

または

if (!string.IsNullOrEmpty(Session["emp_num"] as string)) 
{ 
} 

これは変数が存在しない場合はnullを返すか、ではないだろう文字列。

+0

ありがとうございます。 –

7
if (HttpContext.Current.Session["emp_num"] != null) 
{ 
    // code if session is not null 
} 
  • で上記のすべて失敗した場合。
関連する問題