C#未处理的异常:System.NullReferenceException:对象引用未设置为对象的实例

本文关键字:设置 对象 实例 NullReferenceException 未处理 异常 System 对象引用 | 更新日期: 2023-09-27 18:02:09

你好,我对理解这段代码的原因有问题:

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:line中的NameApp.Main((21

C#未处理的异常:System.NullReferenceException:对象引用未设置为对象的实例

您的线路

me = you as Person;

正在失败,并将null分配给me,因为您无法将基类类型对象强制转换为子类。

作为(C#参考(

as运算符类似于强制转换操作。但是,如果转换不可能,因为返回null而不是引发异常。

您可能希望将person强制转换为object,因为meObject,但you不是人。

此代码将始终将me设置为空

   Object you = new Object();
   me = you as Person;

因为Obejct而不是

但人是object:

object you = new Person();
me = you as Person;

如果使用as关键字进行强制转换,并且强制转换不可能,则返回null。然后在您的情况下,您调用me.GetType(),此时menull,因此会抛出异常。

如果像(Person) objectOfTypeThatDoesNotExtendPerson一样进行强制转换,则会在强制转换时立即抛出异常。

Object you = new Object();
me = you as Person;

you是一个对象,而不是Person,因此you as Person将简单地返回null。

me = you as Person;

如果you不能被广播到Person,则me就是null(这就是您的情况,因为new Object()不能被广播给Person

如果对象不是您请求的类型,as运算符将返回null。

me = you as Person;

你是一个Object,而不是Person,所以(你作为Person(是null,所以我是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
}

对象不能强制转换为Person。它是面向对象编程的原理。

对象是Person的父类。每个类都继承它,

您可以将Person强制转换为Object,但不能将Object强制转换为Person