簡體   English   中英

Xamarin中的System.NullReferenceException

[英]System.NullReferenceException in 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;
    }
}

在此處輸入圖片說明

根據您提供的代碼,有兩種不同的可能性。

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();
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM