【发布时间】:2014-11-14 17:29:23
【问题描述】:
我在Universe 类中有以下方法:
public IWorld CreateWorld(string name) {
//Validations and stuff...
IWorld world = new World(name);
worlds.Add(name, world);
return world;
}
创建一个新的World 实例,并将其添加到Dictionary<string, IWorld>。然后,我继续返回添加到字典中的相同引用。
到目前为止一切顺利。
在同一个Universe类中,我也有如下方法:
public void DestroyWorld(string name) {
//Validations and stuff...
IWorld world = worlds[name];
worlds.Remove(name);
world.Dispose();
world = null; // <- Setting the object to null
}
这里我从字典中获取对象引用,处理它,然后将其设置为 null。
在这个项目之外,我有我的Main 类:
public static void Main(strig[] args) {
IWorld world = Universe.Instance.CreateWorld("Solarius");
Console.WriteLine(world.Age); //Prints out the world's age
Universe.Instance.DestroyWorld(world.Name);
Console.WriteLine(world.Age); //NullPointerException not being thrown! Prints out the same world's age
}
为什么会这样?如果我在Universe.DestroyWorld 方法中将引用设置为null,为什么我可以调用world.Age?
存储在字典中的引用与我在 Main 类中操作的引用不一样吗?
【问题讨论】:
-
我没有看到定义年龄的代码。可以提供一下吗?
-
只是
IWorld接口上的一个属性:int Age { get; } -
为什么 DestroyWorld 的代码采用字符串参数而不是 IWorld?
-
我有一个采用
IWorld的方法的重载,但我真的需要一个字符串,因为它是字典的键
标签: c# .net dictionary reference