我有这样的代码:无法克服System.NullReferenceException
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Zad_8.Chapter11
{
class Program
{
static void Main(string[] args)
{
Cat[] cats = new Cat[10];
for (int i = 0; i < 10; i++)
{
cats[i].Name = "Cat " + sequence.NextValue();
}
for (int i = 0; i < 10; i++)
{
Console.WriteLine(cats[i].Name);
}
}
}
}
这是我在我的命名空间中的类第11章
namespace Zad_8.Chapter11
{
public class Cat
{
private string name = "Cat";
private string color;
public string Name
{
get { return this.name; }
set { this.name = value; }
}
public Cat(string name)
{
this.name = name;
}
}
}
这个类也是我的命名空间第11章
namespace Zad_8.Chapter11
{
public class sequence
{
private static int current = 0;
private sequence()
{ }
public static int NextValue()
{
current++;
return current;
}
}
}
我的目标是创建10个对象 - 猫(类型),并给它们起名称像CatN,其中N是它们的编号。
我有class Cat + name属性+ get和set。 我有班级的序列,它会给我数字从1到10
在主要功能我想创建数组类型Cat和for循环给这10个索引数组中的每个元素名称CAT +它的数字由序列。
在我的错误列表中没有错误,我尝试了很多东西,例如只打印10次Cat等。但是每次它都会抛出此异常'System.NullReferenceException。
我在MSDN阅读,但没有得到足够的东西来解决这个问题。 (f11)调试模式,似乎一切都很好,但当它开始读取与“cats [i] .Name =”Cat“+ sequence.NextValue();”可以继续,只是坚持它,编译器无法继续前进。我在我的数组中看到这个索引是空的,我不确定,但它可能是问题。
任何人都可以告诉我该怎么做对吗?
我想这是一个讨厌和无聊的问题,但我是新手,必须通过这个,所以请不要讨厌这个职位。
'Cat'是'class','class'是一个引用类型。引用类型用'null'值初始化。一个引用类型的数组将是一个'null'值的数组。所以对于每个'猫',你需要一个'新猫'。 – crashmstr 2014-08-29 17:33:36