【问题标题】:System.NullReferenceException HandledSystem.NullReferenceException 已处理
【发布时间】:2013-04-25 07:48:50
【问题描述】:

这是我为一个简单的基于事件的加法器编写的代码,这是我经常遇到的错误:对象引用未设置为对象的实例。

我是初学者,那么我的错误是什么?我错过了什么?谢谢。

private void txtTwo_TextChanged(object sender, TextChangedEventArgs e)
{
            int numberOne, numberTwo, number3;
            if (int.TryParse(txtOne.Text, out numberOne))
            {
                // DO NOTHING
            }
            else
            {
                MessageBoxButton buttons = MessageBoxButton.OK;
                MessageBoxImage icon = MessageBoxImage.Error;
                MessageBox.Show("Not An Integer! Only Integers Allowed !", "Error : First Number", buttons, icon);
                txtOne.Clear();
            }
            if (int.TryParse(txtTwo.Text, out numberTwo))
            {
                //DO NOTHING
            }
            else
            {
                MessageBoxButton buttons2 = MessageBoxButton.OK;
                MessageBoxImage icon2 = MessageBoxImage.Error;
                MessageBox.Show("Not An Integer! Only Integers Allowed !", "Error : Second Number", buttons2, icon2);
                txtTwo.Clear();
            }

            number3 = numberOne + numberTwo;
            string num3 = number3.ToString();
            txtOut.Text = num3;
}

【问题讨论】:

  • 您究竟从哪里得到异常?
  • 最后一行:txtOut.Text = num3;我很困惑为什么它会抛出异常。
  • 我认为 num3 不能为空,因为 number3 将始终具有默认的非空值。更像 txtOut 没有实例化。 txOut 在 Windows 窗体上是否可见?
  • NullReferenceException 的几乎所有情况都是相同的。请参阅“What is a NullReferenceException in .NET?”获取一些提示。
  • num3 不能是null

标签: c# .net nullreferenceexception


【解决方案1】:

所以终于明白了。

嗯,num3 不能为空,因为它是一个值类型,这意味着 txt3 为空。 txtOut 为空,因为在 XAML 中设置 txtTwo 的 Text 属性时引发了 TextChanged 事件,这可能发生在创建 txtOut 文本框之前。

所以解决方法是从 XAML 中移除 TextChanged 事件并将其放入构造函数中,在 InitializeComponent 之后:

public MainWindow() {
    InitializeComponent();
    txtTwo.TextChanged += txtTwo_TextChanged;
}

【讨论】:

    【解决方案2】:

    在这种情况下,txtOut 必须为 null,因为 num3 已被初始化。尝试在设计器中重命名 txtOut 控件或删除并重新创建它。

    【讨论】:

      猜你喜欢
      • 2018-09-03
      • 2022-11-19
      • 2013-09-04
      • 1970-01-01
      • 1970-01-01
      • 2015-12-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多