为什么在构造函数中抛出异常会导致空引用? [英] Why throwing exception in constructor results in a null reference?

查看:21
本文介绍了为什么在构造函数中抛出异常会导致空引用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么在构造函数中抛出异常会导致空引用?例如,如果我们运行下面的代码,teacher 的值为null,而st.teacher 则不是(创建了一个Teacher 对象).为什么?

Why throwing exception in constructor results in a null reference? For example, if we run the codes below the value of teacher is null, while st.teacher is not (a Teacher object is created). Why?

using System;

namespace ConsoleApplication1
{
  class Program
  {
    static void Main( string[] args )
    {
      Test();
    }

    private static void Test()
    {
      Teacher teacher = null;
      Student st = new Student();
      try
      {
        teacher = new Teacher( "", st );
      }
      catch ( Exception e )
      {
        Console.WriteLine( e.Message );
      }
      Console.WriteLine( ( teacher == null ) );  // output True
      Console.WriteLine( ( st.teacher == null ) );  // output False
    }
  }

  class Teacher
  {
    public string name;
    public Teacher( string name, Student student )
    {
      student.teacher = this;
      if ( name.Length < 5 )
        throw new ArgumentException( "Name must be at least 5 characters long." );
    }
  }

  class Student
  {
    public Teacher teacher;
  }

}

推荐答案

构造函数永远不会完成,因此赋值永远不会发生.不是从构造函数返回 null(或者有一个空对象"——没有这样的概念).只是你从来没有给teacher赋值,所以它保留了之前的值.

The constructor never completes, therefore the assignment never occurs. It's not that null is returned from the constructor (or that there's a "null object" - there's no such concept). It's just that you never assign a new value to teacher, so it retains its previous value.

例如,如果您使用:

Teacher teacher = new Teacher("This is valid", new Student());
Student st = new Student();
try
{
    teacher = new Teacher("", st);
}
catch (... etc ...)

... 那么你仍然会有这是有效的"老师.name 变量仍然不会在该 Teacher 对象中赋值,因为您的 Teacher 构造函数缺少一行,例如:

... then you'll still have the "This is valid" teacher. The name variable still won't be assigned a value in that Teacher object though, as your Teacher constructor is missing a line such as:

this.name = name;

这篇关于为什么在构造函数中抛出异常会导致空引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆