如果条件错误?

时间:2013-08-30 12:27:08

标签: c# windows-phone-8

我提出了一个条件,即if变量为null。但是由于null变量,这段代码仍会破坏应用程序。

CODE:

var page = IsolatedStorageSettings.ApplicationSettings["qsPage"];
var hash = IsolatedStorageSettings.ApplicationSettings["Ayath"];
if (page == null && hash == null)
// or if i use if (page == null || hash == null)
{    
MessageBox.Show("No Bookmark has been saved !");
}
else
{
NavigationService.Navigate(new Uri("/myWeb.xaml?Page=" + page + "&id=" + hash, UriKind.Relative));
}

3 个答案:

答案 0 :(得分:1)

在if条件中使用&&,页面可以为null但是散列号为no,因此它将转到else clausule,并且由于页面为null,它将失败。

尝试将&&替换为||这样,每当页面OR哈希为空时,它都会显示消息框。

更新:由于页面和哈希变量是字符串,您需要使用String.IsNullOrWhiteSpace测试它们,这样:

var page = IsolatedStorageSettings.ApplicationSettings["qsPage"];
var hash = IsolatedStorageSettings.ApplicationSettings["Ayath"];
if (string.IsNullOrWhiteSpace(page.ToString()) || string.IsNullOrWhiteSpace(hash.ToString()))
{
    MessageBox.Show("No Bookmark has been saved !");
}
else
{
    NavigationService.Navigate(new Uri("/myWeb.xaml?Page=" + page + "&id=" + hash, UriKind.Relative));
}

答案 1 :(得分:1)

尝试:

if (page == null || hash == null)

相反。您的查询要求两个变量都为空。

答案 2 :(得分:1)

您必须检查IsolatedStorageSettings.ApplicationSettings["qsPage"];是否返回null或任何值。试试这个。

 object pagedata = null,hashdata = null;
if(IsolatedStorageSettings.ApplicationSettings.Contains("qsPage") && IsolatedStorageSettings.ApplicationSettings.Contains("Ayath"))
{
  var page = IsolatedStorageSettings.ApplicationSettings["qsPage"];
  var hash = IsolatedStorageSettings.ApplicationSettings["Ayath"];

  pagedata = page;
  hashdata = hash;
}
 if (pagedata == null && hashdata == null)
// or if i use if (page == null || hash == null)
{    
 MessageBox.Show("No Bookmark has been saved !");
}
else
{
 NavigationService.Navigate(new Uri("/myWeb.xaml?Page=" + pagedata + "&id=" + hashdata, UriKind.Relative));
}