为什么扔在构造结果例外空引用? [英] Why throwing exception in constructor results in a null reference?
问题描述
为什么扔在构造结果例外空引用?
为例,如果我们运行下面老师的值码为空,而st.teacher不是(创建一个老师对象)。为什么?
使用系统;
命名ConsoleApplication1
{
类节目
{
静态无效的主要(字串[] args)
{
测试( );
}
私有静态无效测试()
{
老师老师= NULL;
学生ST =新学生();
试
{
老师=新老师(,ST);
}
赶上(例外五)
{
Console.WriteLine(e.Message);
}
Console.WriteLine((老师== NULL)); //输出真正的
Console.WriteLine((st.teacher == NULL)); //输出False,
}
}
班主任
{
公共字符串名称;
公共老师(字符串名称,学生的学生)
{
student.teacher =这一点;
如果(name.Length小于5)
抛出新的ArgumentException(名称必须至少5个字符长。);
}
}
类学生
{
公众教师的教师;
}
}
构造函数永远不会完成,从未因此发生转让。这不是空从构造函数返回(或者说有一个空对象 - 有没有这样的概念)。它只是你从来没有分配一个新值教师
,因此它保留了其原来的值。
例如,如果你使用:
教师教师=新老师(这是有效的,新的学生());
学生ST =新学生();
试
{
老师=新老师(,ST);
}
赶上(...等...)
..然后你仍然有这是合法的老师。在名称
变量仍然不会被分配了一个值,虽然教师
对象,因为你的教师
构造缺少线,如:
this.name =名称;
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;
}
}
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.
For example, if you use:
Teacher teacher = new Teacher("This is valid", new Student());
Student st = new Student();
try
{
teacher = new Teacher("", st);
}
catch (... etc ...)
... 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屋!