Xamarin中的System.NullReferenceException

时间:2015-02-13 22:05:50

标签: c# xamarin

我编写了以下代码行来检查用户是否在SettingViewController中输入密码。我正在使用以下代码进行测试,然后用户导航到settingViewController页面。但是,我收到了SystemNullReference错误。

SettingViewController callSetting = this.Storyboard.InstantiateViewController ("SettingViewController") as SettingViewController;

        if (string.IsNullOrEmpty(callSetting.sSettings.password)==true) 
            Console.WriteLine("is null or empty");
        else 
            Console.WriteLine (callSetting.sSettings.password);

这是我的ServerSettings类:

public class ServerSettings
{

    public string server{ get; set;}
    public string port { get; set;}
    public string username { get; set;}
    public string password { get; set;}
    public string userid { get; set;}

    public ServerSettings ()
    {

    }

}

这是我的SettingViewController类:

partial class SettingViewController : UIViewController
    {
    public ServerSettings sSettings;
    public SettingViewController (IntPtr handle) : base (handle)
    {
        this.Title = "Settings";

    }

    public override void ViewWillDisappear (bool animated)
    {
        sSettings.server=serverTF.Text;
        sSettings.port = portTF.Text;
        sSettings.password = passwordTF.Text;
        sSettings.userid = inboxuserTF.Text;
        sSettings.username = usernameTF.Text;
    }
}

enter image description here

1 个答案:

答案 0 :(得分:1)

根据您提供的代码,有两种不同的可能性。

A)callSettingnull

B)callSetting.sSettingsnull

您可以添加以下内容:

SettingViewController callSetting = this.Storyboard.InstantiateViewController ("SettingViewController") as SettingViewController;

 if (callSetting == null)
   throw new Exception("callSetting is null"); // Or if you can handle having a null callSetting then correct for it, but realistically this is a problem, so I'd throw an Exception

 if (callSetting.sSetting == null)
   throw new Exception("sSetting is null"); // Or if you can handle having a null callSetting.sSetting then correct it (such as using a default value).

 if (string.IsNullOrEmpty(callSetting.sSettings.password)==true) 
    Console.WriteLine("is null or empty");
 else 
    Console.WriteLine (callSetting.sSettings.password);

另外作为旁注,你可以简化这一行

 if (string.IsNullOrEmpty(callSetting.sSettings.password)==true) 

 if (string.IsNullOrEmpty(callSetting.sSettings.password)) 

编辑:根据已修改的问题,您需要将代码修改为

public SettingViewController (IntPtr handle) : base (handle)
{
    this.Title = "Settings";
    this.sSettings = new ServerSettings();
}