使用未分配的局部变量(Object) [英] Use of unassigned local variable (Object)

查看:307
本文介绍了使用未分配的局部变量(Object)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Person tempPerson;

Console.WriteLine("Enter the name of this new person.");
tempPerson.Name = Convert.ToString(Console.ReadLine());

Console.WriteLine("Now their age.");
tempPerson.Age = Convert.ToInt32(Console.ReadLine());

peopleList.Add(tempPerson);

RunProgram();

tempPerson.Name 显示Unassigned use of local variable'tempPerson'。下面是创建每个Person对象的类。

At tempPerson.Name, the error list displays "Unassigned use of local variable 'tempPerson'. Below is the class where each Person object is created.

class Person : PersonCreator
{
    public Person(int initialAge, string initialName)
    {
        initialAge = Age;
        initialName = Name;
    }
    public int Age
    {
        set
        {
            Age = value;
        }
        get
        {
            return Age;
        }
    }
    public string Name
    {
        set
        {
            Name = value;
        }
        get
        {
            return Name;
        }
    }
}   

我不明白为什么这是一个问题。在tempPerson.Age,没有任何问题,只运行tempPerson.Age程序没有带来错误。我的Person类有问题吗?

I don't understand why this is a problem. At tempPerson.Age, there is no problem at all. Running the program with only tempPerson.Age brings no errors. Is there a problem with my Person class?

推荐答案

tempPerson 初始化为 Person 对象,因此它是 null - 任何调用该变量的任何成员将导致一个 NullReferenceException

tempPerson is never initialized to a Person object, so it is null - any call to any member of the variable will result in a NullReferenceException.

您必须在使用前初始化变量:

You must initialize the variable before usage:

var tempPerson = new Person();

这篇关于使用未分配的局部变量(Object)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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