问题描述
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)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!