c# - 在 Request.QueryString 中避免 NullReferenceException

标签 c# asp.net query-string nullreferenceexception

如果页面查询字符串中未指定 mode,此代码将抛出 NullReferenceException:

bool isAdvancedMode = Request.QueryString["mode"].Equals("advanced");

这就是我解决这个问题的方法:

bool isAdvancedMode = (Request.QueryString["mode"] + "").Equals("advanced");

这是标准做法还是 hack?

最佳答案

您可以使用 null-coalescing operator :

bool isAdvancedMode = (Request.QueryString["mode"] ?? String.Empty).Equals("advanced");

编辑:如果你想重新使用这个逻辑,试试这个扩展方法:

public static bool EqualIfExists(this string source, string comparison)
{
    return source != null && source.Equals(comparison);
}

Request.QueryString["mode"].EqualIfExists("advanced")

添加更多覆盖以匹配 Equals 签名。我不确定这是否是个好名字(我认为不是)。

关于c# - 在 Request.QueryString 中避免 NullReferenceException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17726781/

相关文章:

Node.JS GET/参数

rust - 如何解码 URL 并将查询字符串作为 HashMap?

java - 从干净代码的角度来看,为什么我们应该避免定义具有三个以上参数的方法?

C# 'Index was outside the bounds of the array.' 用于一个数组而不是另一个

c# - C#中线程安全的可破坏事件触发类

c# - 在 ItemTemplate 中使用 Container.DataItem

c# - 有生成图形轮廓的算法吗?

asp.net - 如何在 SQL 中透视表

javascript - 压缩脚本和样式并将所有 js 和样式引用组合成单个引用以优化站点性能

mysql - Google Analytics Reporting API 与查询参数