使用未分配的局部变量(Object)

Bog*_*y B -2 c# class list 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();
Run Code Online (Sandbox Code Playgroud)

tempPerson.Name,错误列表显示"未分配使用局部变量'tempPerson'.下面是创建每个Person对象的类.

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;
        }
    }
}   
Run Code Online (Sandbox Code Playgroud)

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

Ode*_*ded 9

tempPerson永远不会初始化为一个Person对象,所以它是null- 对变量的任何成员的任何调用都将导致a NullReferenceException.

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

var tempPerson = new Person();
Run Code Online (Sandbox Code Playgroud)