获取错误对象引用未设置为对象的实例

本文关键字:对象 实例 设置 取错误 对象引用 获取 | 更新日期: 2023-09-27 17:53:56

我正在创建windows窗体语音重新定位应用程序,但不知何故无法修复对象引用问题:有没有人能告诉我哪里出错了,因为我正在获取错误对象引用,而不是设置为下面代码中的对象实例。

public partial class Form1 : Form
    {
        SpeechSynthesizer ss = new SpeechSynthesizer();
        PromptBuilder pb = new PromptBuilder();
        SpeechRecognitionEngine sre = new SpeechRecognitionEngine();
        Choices list;
        public Form1()
        {
            InitializeComponent();
        }
        private void btnStart_Click(object sender, EventArgs e)
        {
            btnStart.Enabled = false;
            btnStop.Enabled = true;
            try
            {
                list.Add(new string[] { "Hello", "Open Chrome", "Close", "What is the current time", "Thank You" });
                Grammar gr = new Grammar(new GrammarBuilder(list));
                try
                {
                    sre.RequestRecognizerUpdate();
                    sre.LoadGrammar(gr);
                    sre.SpeechRecognized += new EventHandler<SpeechRecognizedEventArgs>(sre_SpeechRecognized);
                    sre.SetInputToDefaultAudioDevice();
                    sre.RecognizeAsync(RecognizeMode.Multiple);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "Exception Caught");
                }
            }
            catch (Exception exception)
            {
                MessageBox.Show(exception.Message, "Exception Caught");
            }
        }
        void sre_SpeechRecognized(object sender, SpeechRecognizedEventArgs e)
        {
            switch (e.Result.Text.ToString())
            {
                case "Hello":
                    ss.SpeakAsync("Hello There");
                    break;
                case "Open Chrome":
                    System.Diagnostics.Process.Start("Chrome", "https://www.google.com");
                    break;
                case "Close":
                    Application.Exit();
                    break;
                case "What is the current time":
                    ss.SpeakAsync("Current time is :" + DateTime.UtcNow.ToLongDateString());
                    break;
                case "Thank You":
                    ss.SpeakAsync("Thank You for using this service");
                    break;
                default:
                    ss.SpeakAsync("Please correct your choice");
                    break;
            }
            txtContents.Text = e.Result.Text.ToString() + Environment.NewLine;
        }
        private void btnStop_Click(object sender, EventArgs e)
        {
            sre.RecognizeAsyncStop();
            btnStart.Enabled = true;
            btnStop.Enabled = false;
        }
    }

获取错误对象引用未设置为对象的实例

代替

Choices list;

Choices list = new Choices();

原因:您甚至在初始化list之前就使用它。

list.Add(new string[] { "Hello", "Open Chrome", "Close", "What is the current time", "Thank You" });