如何判断没有值时传递的内容

Pos*_*Guy 2 c# asp.net

对于此代码,如果查询字符串中没有值,您如何知道返回null?

HttpContext context = HttpContext.Current;
string strValue = context.Request[name];
Run Code Online (Sandbox Code Playgroud)

我问,因为我不知道在.NET框架中很多情况下返回的是什么,当你没有得到它不存在的预期值时.

因此,如果context.Request[name];调用并且查询字符串中不存在该名称,您如何知道它返回null或空字符串以便我可以正确处理它不存在的情况?

Jus*_*ner 8

使用String.IsNullOrEmpty()来检查null或空字符串:

string strValue = !String.IsNullOrEmpty(context.Request[name]) ?? 
    context.Request[name] : "Some Default Value";
Run Code Online (Sandbox Code Playgroud)

或者,如果您没有要设置的默认值,可以稍后进行检查:

if(String.IsNullOrEmpty(strValue))
{
    // It's Null Or Empty
}
else
{
    // It's Not
}
Run Code Online (Sandbox Code Playgroud)

更新

刚刚看到评论.如果你想弄清楚是否引用了Params集合中不存在的密钥(这是你通过简写使用的那个),那么请查看MSDN文档.

在这种情况下,Params是一个System.Collections.Specialized.NavmeValueCollection.文档在这里.根据文档,null当在集合中找不到密钥时,确实返回了一个值.

因此您不必使用String.IsNullOrEmpty().你可以:

string strValue = context.Request[name] ?? "Some Default Value";
Run Code Online (Sandbox Code Playgroud)

如果要设置默认值,或者null另行检查.