我正在尝试编写一个包含数字生物的模型.在该模型中,我将环境置于固定的二维阵列中,但每个细胞需要包含其中的生物列表.我尝试使用锯齿状数组,但由于整个程序运行中占用元素的数量变化很大,我需要使用比数组更灵活的东西.我已经尝试制作类型列表的二维数组,但我得到它的错误.
List<Creature>[,] theWorld;
public Environment()
{
List<Creature>[,] theWorld = new List<Creature>[100,100];
}
public void addCreature(Creature c)
{
for (int x = 0; x < 100; x++)
{
for (int y = 0; y < 100; y++)
{
theWorld[x, y].Add (c);
} } }
Run Code Online (Sandbox Code Playgroud)
这是我试图在开始时声明数组的片段,作为保存(生物体)列表的类型,稍后我尝试将生物(c)添加到每个元素中的每个元素中.阵列.
当我运行它时,我得到以下错误信息 -
"HGT_sim_2.exe中发生了'System.NullReferenceException'类型的未处理异常
附加信息:对象引用未设置为对象的实例."
和"World [x,y] .Add(c);" 突出显示.
如果有人能告诉我我做错了什么,甚至更好,一个解决问题的办法,那就太棒了.谢谢你提前!
你的所有数组最初都包含很多空值.你需要实际创建列表......
for(int x = 0 ; x < 100 ; x++)
for(int y = 0 ; y < 100 ; y++)
theWorld[x,y] = new List<Creature>();
Run Code Online (Sandbox Code Playgroud)
但就个人而言,我认为这将是一种昂贵的做事方式......
这在一定程度上取决于数据是否"稀疏" - 即通常采用的大多数细胞?例如,一种简单(但可能更有效)的方法是使用类似多地图的方法; 即
Point pt = new Point(x,y);
theWorld.Add(pt, someCreature);
Run Code Online (Sandbox Code Playgroud)
在哪里theWorld可能是EditableLookup<Point, Creature>(使用EditableLookup<,>" MiscUtil ").这样,你仍然可以通过坐标查询它,并在坐标上有多个生物,但你不必为每个细胞分配空间.因为它作为字典起作用,它仍然很快.不像平面阵列那么快,但它会扩展到更大(稀疏)的网格...当然,如果网格在每个单元格上都有生物,那么它可能会更贵!因此需要了解您的数据.
这是修复方法:
List<Creature>[,] theWorld;
public Environment()
{
theWorld = new List<Creature>[100,100]; // Remove the type, you were creating a new list and throwing it away...
for(int x = 0 ; x < 100 ; x++)
for(int y = 0 ; y < 100 ; y++)
theWorld[x,y] = new List<Creature>();
}
public void addCreature(Creature c)
{
for (int x = 0; x < 100; x++)
{
for (int y = 0; y < 100; y++)
{
theWorld[x, y].Add (c);
} } }
Run Code Online (Sandbox Code Playgroud)