C#Newbie - 嵌套方法又有一个System.NullReferenceException-Object错误

时间:2013-12-09 23:26:22

标签: c#

出于学习的目的,我设置了一种方法来调用另一种方法来显示我通过用户输入定义的值。但是,我最终得到了一个令人讨厌的错误:

  

System.NullReferenceException - 未将对象引用设置为对象的实例

有人可以解释我正在做的导致错误的事情;并且,在不更改代码的情况下完成此工作(保留嵌套方法)。

Program.cs的

namespace Test
{
    class Program
    {
        static void Main(string[] args)
        {
            Parent theParent = new Parent();

            Console.WriteLine("Enter Child Name:");
            string input = Console.ReadLine();
            theParent.Child.Name = input;

            theParent.FirstMethod();
            Console.ReadLine();
        }
    }
}

Parent.cs

namespace Test
{
    class Parent
    {
        public Child Child = new Child();   //I changed this line.  It was originally only 'public Child Child'

        public void FirstMethod()
        {
            Child newChild = new Child();
            newChild.SecondMethod();
        }
    }
}

Child.cs

namespace Test
{
    class Child
    {
        private string name;

        public string Name
        {
            get { return name; }
            set { name = value; }
        }

        public void SecondMethod()
        {
            Parent theParent = new Parent();
            Console.WriteLine(theParent.Child.Name.ToString());
        }
    }
}

2 个答案:

答案 0 :(得分:4)

引用类型(类)初始化为null。在Parent类型中,您可以像这样声明Child

public Child Child;

这会产生Child字段null。你需要内联初始化..或者在构造函数中设置它:

public Child Child = new Child();

...或...

public Parent() {
    Child = new Child();
}
声明Parent对象时

..甚至内联:

Parent theParent = new Parent() { Child = new Child() };

对于像这样的任何其他人也一样。

答案 1 :(得分:1)

Childnull

首先,您要创建一个新的Parent

Parent theParent = new Parent();

这有一个public字段child(注意:使用属性,而不是公共字段):

public Child Child; 

如您所见:这是未经实例化的。

然后你使用这个孩子:

theParent.Child.Name = input;

childnull!因此,NullReferenceException

您必须安装child字段:

public Child Child = new Child();

或者在另一个地方,这取决于你。

关于公共领域的旁注:您通过提供对实例成员的直接访问来打破封装。你应该使用getter& setters(在C#中由一个属性方便地提供)。

新情况:

void Main()
{
    Parent theParent = new Parent();
    string input = "jack";
    theParent.Child.parent = theParent; // ADD THIS
    theParent.Child.Name = input;

    theParent.FirstMethod();
}

class Parent
    {
        public Child Child = new Child();   //I changed this line.  It was originally only 'public Child Child'

        public void FirstMethod()
        {
        //  Child.parent = this; // REMOVE THIS
            Child.SecondMethod();
        }
    }

class Child
{
   public Parent parent;
   private string name;

   public string Name
   {
       get { return name; }
       set { name = value; }
   }

   public void SecondMethod()
   {
       Console.WriteLine(parent.Child.Name);
   }
}

输出:

  

插孔