【问题标题】:Check if Page.RouteData.Values has a value检查 Page.RouteData.Values 是否有值
【发布时间】:2012-12-09 01:06:04
【问题描述】:

运行时出现错误

string quote = Page.RouteData.Values["quote"].ToString() ?? string.Empty;

错误:对象引用未设置为对象的实例。

我了解 ToString 导致错误,因为 Page.RouteData.Values["quote"] 为空/null。

在我们执行 ToString 之前,如何检查 Page.RouteData.Values["quote"] 是否有值?

【问题讨论】:

    标签: c# asp.net routes


    【解决方案1】:

    怎么样:

    if (Page.RouteData.Values["quote"] != null) {
        string quote = Page.RouteData.Values["quote"].ToString() ?? string.Empty;
    }
    

    string quote = ((Page.RouteData.Values["quote"] != null) ? Page.RouteData.Values["quote"].ToString() : string.Empty);
    

    【讨论】:

      【解决方案2】:

      试试这个

      var quote = Page.RouteData.Values["quote"]?.ToString() ?? string.Empty;
      

      【讨论】:

        猜你喜欢
        • 2017-12-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-07-16
        • 2012-11-06
        • 1970-01-01
        • 2023-02-05
        • 1970-01-01
        相关资源
        最近更新 更多