"Object reference not set to an instance of an object" 在 Xamarin.android c#

"Object reference not set to an instance of an object" in Xamarin.android c#

我只是想用 https://docs.microsoft.com/en-us/learn/modules/create-a-mobile-app-with-xamarin-forms/5-exercise-create-phone-number-translator-app 教程中的 Xamarin.android 制作一个简单的应用程序 但是当我构建它时,应用程序崩溃了。我尝试调试并在 OnTranslate 方法中遇到错误 System.NullReferenceException: Object reference not set to an instance of an object.

我尝试将声明变量的值设置为空。尝试使用空运算符。

这是我的代码

    {
        Entry phoneNumberText = null;
        Button translateButton = null;
        Button callButton = null;
        string translatedNumber;
        public MainPage()
        {
           /*
               Some design code
           */
            translateButton.Clicked += OnTranslate;
            this.Content = panel;
        }

         void OnTranslate(object sender, EventArgs e)
        {
            string enterednum = phoneNumberText.Text;
            translatedNumber = Core.PhonewordTranslator.ToNumber(enterednum);

            if (!string.IsNullOrEmpty(translatedNumber))
            {
                callButton.IsEnabled = true;
                callButton.Text = "Call" + translatedNumber;
            }
            else
            {
                callButton.IsEnabled = false;
                callButton.Text = "Call";
            }
        }

我已经在我的设计代码中设置了入口和那两个按钮的值。 这是将字符串转换为数字的方法

        {
            if (string.IsNullOrWhiteSpace(raw))
                return null;
            raw = raw?.ToUpperInvariant();
            var newNumber = new StringBuilder();

            foreach (var c in raw)
            {
                if (" -0123456789".Contains(c))
                    newNumber?.Append(c);
                else
                {
                    var result = TranslateToNumber(c);
                    if (result != null)
                        newNumber.Append(result);
                    //bad string?
                    else return null;
                }
            }
            return newNumber?.ToString();
        }

        static bool Contains(this string keystring, char c){
            return keystring?.IndexOf(c) >= 0;
            }

        static readonly string[] digits =
        {
            "ABC", "DEF", "GHI", "JKL", "MNO", "PQRS", "TUV", "WXYZ"
        };
        static int? TranslateToNumber(char c)
        {
            for(int i = 0; i<digits.Length; i++)
            {
                if (digits[i].Contains(c))
                    return 2 + i;
            }
            return null;
        }
    }

debugging stops automatically at translateButton.Clicked += OnTranslate;

这应该能告诉你一些事情。在这里你声明了一个按钮但从未实例化它

Button translateButton = null;

所以稍后当您尝试分配事件处理程序时,您的按钮仍然为空,这会导致异常

translateButton.Clicked += OnTranslate;

您需要先实例化按钮

translateButton = new Button();