String等于NULL时出现异常错误

时间:2014-04-03 20:10:12

标签: c# string visual-studio-2012 windows-phone-8 null

我尝试在首次启动应用时设置一些默认设置。我尝试检测String何时等于null但是它一直抛出异常错误,任何想法?

// Code to execute when the application is launching (eg, from Start)
// This code will not execute when the application is reactivated
private void Application_Launching(object sender, LaunchingEventArgs e)
{
    IsolatedStorageSettings settings = IsolatedStorageSettings.ApplicationSettings;

    String isFirstRun = settings["firstrun"] as string;

    if (isFirstRun == null)
    {
        settings["firstrun"] = "no";
        settings["defaultLocation"] = "Dulles, VA";
        settings["defaultTest"] = "Speed Test";
        settings.Save();
    }
}

异常错误是:

  

MyConnection.DLL!MyConnection.App.RootFrame_NavigationFailed(object sender,System.Windows.Navigation.NavigationFailedEventArgs e)第103行C#

1 个答案:

答案 0 :(得分:2)

首先应该在使用它之前将密钥添加到字典(IS)中 - 检查IS是否包含第一次运行的密钥:

IsolatedStorageSettings settings = IsolatedStorageSettings.ApplicationSettings;

if (!settings.Contains("firstrun"))
{
    settings.Add("firstrun", "no");
    settings.Add("defaultLocation", "Dulles, VA");
    settings.Add("defaultTest", "Speed Test");
    settings.Save();
}