运行时出现错误
string quote = Page.RouteData.Values["quote"].ToString() ?? string.Empty;
错误:对象引用未设置为对象的实例。
我了解 ToString 导致错误,因为 Page.RouteData.Values["quote"] 为空/空。
在执行 ToString 之前,如何检查Page.RouteData.Values ["quote"] 是否有值?
怎么样:
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);
尝试这个
var quote = Page.RouteData.Values["quote"]?.ToString() ?? string.Empty;