C#未处理的异常:System.NullReferenceException:对象引用未设置为对象的实例
您好,我很难理解这段代码的原因:C#未处理的异常:System.NullReferenceException:对象引用未设置为对象的实例,c#,casting,nullreferenceexception,gettype,C#,Casting,Nullreferenceexception,Gettype,您好,我很难理解这段代码的原因: using System; class Person { public Person() { } } class NameApp { public static void Main() { Person me = new Person(); Object you = new Object(); me = you as Person; //me = (P
using System;
class Person
{
public Person()
{
}
}
class NameApp
{
public static void Main()
{
Person me = new Person();
Object you = new Object();
me = you as Person;
//me = (Person) you;
System.Console.WriteLine("Type: {0}", me.GetType()); //This line throws exception
}
}
引发此异常:
using System;
class Person
{
public Person()
{
}
}
class NameApp
{
public static void Main()
{
Person me = new Person();
Object you = new Object();
me = you as Person;
//me = (Person) you;
System.Console.WriteLine("Type: {0}", me.GetType()); //This line throws exception
}
}
未处理的异常:System.NullReferenceException:对象引用未设置为对象的实例。
在C:\Users\Nenad\documents\visual studio 2010\Projects\Exercise 11.3\Exercise 11.3\Program.cs中的NameApp.Main()处
21您的线路
me = you as Person;
由于无法将基类类型对象强制转换为子类,因此失败并将null分配给me
as运算符类似于强制转换操作。但是,如果转换
不可能,因为返回null而不是引发异常
您可能希望将
person
转换为对象
,因为me
是对象
,但您
不是人 此代码将始终将me
设置为空
Object you = new Object();
me = you as Person;
因为Obejct不是个人
但人是对象
:
object you = new Person();
me = you as Person;
you
是一个对象,而不是一个人,因此youasperson
将简单地返回null
me = you as Person;
me
为null
如果无法将您的转换为Person
(这就是您的情况,因为新对象()
无法转换为Person如果对象不是您请求的类型,as操作符将返回null
me = you as Person;
您是一个对象,而不是一个人,因此(您作为一个人)为null,因此me为null。当您随后对我调用GetType()时,您会得到一个NullReferenceException。对象不能强制转换为一个人。
public static void Main()
{
Person me = new Person();
Object you = new Object();
// you as person = null
me = you as Person;
//me = (Person) you;
System.Console.WriteLine("Type: {0}", me.GetType()); //This line throws exception
}
这是面向对象编程的一个原则
对象是个人的父类。
每个类都继承它
您可以将人强制转换为对象,但不能将对象强制转换为人如果您使用as
关键字进行强制转换,并且强制转换不可能,它将返回null
。
然后在本例中调用me.GetType()
,此时me
为null
,因此引发异常
如果你像(Person)类型的objectof thetypethat notextendperson
一样施法,则会立即抛出一个异常。很多人指出了显而易见的问题-但是你期望你作为Person
做什么?我只是在按照一本书中的教程进行操作-很可能是作者把“你”和“我”放错了位置,但在同伴网站的勘误表中并没有关于它的信息,所以我只想在这里确认一下,以防我错过了什么。我只是在阅读一本书的教程——很可能是作者错放了“你们”和“我”,但在同伴网站的勘误表中并没有关于它的信息,所以我只想在这里检查一下,以确保我没有遗漏什么。