为了学习的目的,我设置了一个方法来调用另一个方法来显示我通过用户输入定义的值。然而,我最终得到一个讨厌的错误:C#新手 - 嵌套方法又一个System.NullReferenceException - 对象错误
System.NullReferenceException - Object reference not set to an instance of an object
可能有人请解释一下我在做什么引起的错误;并且在不改变代码的情况下进行这项工作(保留嵌套方法)。
的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());
}
}
}
谢谢。当我把“公共儿童儿童”改为“公共儿童儿童=新儿童()”时,那照顾了一个错误。但是,也有同样的错误消息抱怨线“Console.WriteLine(theParent.Child.Name.ToString());”在Child.cs – MKANET
@MKANET:尝试删除'.ToString()'。 'Name'已经是'string'了,所以它不应该有所作为。但是如果'string'是'null',它会抛出一个NullReferenceException。 –
我已经试过了。字符串是空白的。它不会显示给Parent.Child.Name的值(来自之前的用户输入)。 – MKANET