C# 字符串等于NULL时出现异常错误

C# 字符串等于NULL时出现异常错误,c#,string,visual-studio-2012,windows-phone-8,null,C#,String,Visual Studio 2012,Windows Phone 8,Null,我正在尝试在应用程序首次启动时设置一些默认设置。我尝试检测字符串何时等于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, Launc

我正在尝试在应用程序首次启动时设置一些默认设置。我尝试检测字符串何时等于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(对象发送方,System.Windows.Navigation.NavigationFailedEventArgs e)第103行C#


在使用字典(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();
}

在您尝试将其转换为字符串之前,首先检查
设置[“firstrun”]
是否为
null
。更好的是,根本不要抛出它……”但它一直抛出一个异常错误”-确切地说是什么异常?我已经从问题的标题中删除了标记-请注意,在大多数情况下,这比问题更重要。用edits@Liel在铸造之前我做了一个检查,我肯定有点混乱,但它确实有效,而且让我烦恼了好几个小时。我已经尝试了上面的代码(参见我的开场白编辑),但没有成功。我在App.cs中做这些,这会导致问题吗?不知道为什么我第一次尝试时它不起作用!!但是谢谢你,因为它是正确的solution@DanJamesPalmer我希望你已经找到了解决办法。当应用程序第一次运行时,此代码应该有效(稍后您应该用
[“”]
(修改键值)替换那些
Add
)。至于检查,您也可以尝试给我们-但您应该知道,它也会从墓碑模式返回false。