【问题标题】:Use of unassigned local variable (Object)使用未分配的局部变量(对象)
【发布时间】:2012-08-30 09:22:30
【问题描述】:
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,错误列表显示“未分配使用局部变量'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;
        }
    }
}   

我不明白为什么这是个问题。在 tempPerson.Age 处,完全没有问题。仅使用 tempPerson.Age 运行程序不会出现错误。我的 Person 类有问题吗?

【问题讨论】:

    标签: c# list class object


    【解决方案1】:

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

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

    var tempPerson = new Person();
    

    【讨论】:

    • 感谢您的快速回复。设法让我的程序再次运行。
    【解决方案2】:

    您不会通过定义类或声明类类型的变量来创建对象。您必须通过在类上调用 new 来创建对象,否则该变量将被初始化为 null。执行以下操作:

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

    【讨论】:

      【解决方案3】:

      你的 Person 类错了,应该是:

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

      【讨论】:

        【解决方案4】:

        您的变量 tempPerson 刚刚声明,但未初始化。 你必须调用 Person 的构造函数,但这需要一个空的构造函数:

        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));
        

        【讨论】:

          猜你喜欢
          • 2013-10-18
          • 2015-11-09
          • 2012-05-18
          • 1970-01-01
          • 2023-03-29
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多