在C#中确定会话变量是否为空的最佳方法是什么?

80
什么是在ASP.NET C#中检查会话变量是否存在的最佳方法?
我喜欢使用String.IsNullOrEmpty() 来检查字符串,想知道是否有类似于Session的方法。目前我所知道的唯一方法是:
 var session;
 if (Session["variable"] != null)
 {
     session = Session["variable"].ToString();
 }
 else
 {
     session = "set this";
     Session["variable"] = session;
 }
12个回答

0
你正在使用 .NET 3.5 吗?创建一个 IsNull 扩展方法:
public static bool IsNull(this object input)
{
    input == null ? return true : return false;
}

public void Main()
{
   object x = new object();
   if(x.IsNull)
   {
      //do your thing
   }
}

1
可以这样写: public static bool Is(this object input) { return input == null; } - James Curran
你应该小心使用扩展方法。 - Chris Pietschmann
1
我为什么要小心使用扩展方法? - Michael Kniskern
为什么不直接使用 x == null 或 x != null? - Benoit

0
如果你知道它是一个字符串,你可以使用String.IsEmptyOrNull()函数。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接