C# 使用未分配的局部变量(对象)
在C# 使用未分配的局部变量(对象),c#,list,class,object,C#,List,Class,Object,在tempPerson.Name中,错误列表显示“未分配使用局部变量'tempPerson'。下面是创建每个Person对象的类 Person tempPerson; Console.WriteLine("Enter the name of this new person."); tempPerson.Name = Convert.ToString(Console.ReadLine()); Console.WriteLine("Now their age."); tempPerson.Age
tempPerson.Name
中,错误列表显示“未分配使用局部变量'tempPerson'。下面是创建每个Person对象的类
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.Age,根本没有问题。仅使用tempPerson.Age运行程序不会带来任何错误。我的Person类有问题吗?您不能通过定义类或声明类类型的变量来创建对象。您必须通过在类上调用new来创建对象,或者如果变量初始化为null,请执行以下操作:
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
从未初始化为Person
对象,因此它是null
-对变量任何成员的任何调用都将导致NullReferenceException
使用前必须初始化变量:
Person tempPerson = new Person ();
Console.WriteLine("Enter the name of this new person.");
tempPerson.Name = Convert.ToString(Console.ReadLine());
您的Person类错误,应该是:
var tempPerson = new Person();
您的变量tempPerson刚刚声明,但未初始化。 您必须调用Person的构造函数,但这需要一个空构造函数:
class Person : PersonCreator
{
public Person(int initialAge, string initialName)
{
Age = initialAge;
Name = initialName;
}
public int Age
{
set;
get;
}
public string Name
{
set;
get;
}
}
解决这个问题的另一种方法是,我将执行以下操作:
Person tempPerson = new Person();
谢谢你的快速回复。我的程序又能正常运行了。
Console.WriteLine("Enter the name of this new person.");
string name = Convert.ToString(Console.ReadLine());
Console.WriteLine("Now their age.");
string age = Convert.ToInt32(Console.ReadLine());
peopleList.Add(new Person(name, age));