2

运行时出现错误

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

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

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

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

4

2 回答 2

10

怎么样:

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);
于 2012-12-09T01:10:10.457 回答
0

尝试这个

var quote = Page.RouteData.Values["quote"]?.ToString() ?? string.Empty;
于 2017-09-11T10:47:22.993 回答