初学者:如何在多个类中正确更新引用?
在我的任务中,我需要在类之间创建一个链接的数据结构。我遇到的一个问题是,当在同类课堂外宣布参考并更改这些引用时,上一类忽略了更改。示例:
Location location1 = new Location(); // Name null
World world = new World(location1);
location1 = new Location("entrance"); // Name chosen
Console.WriteLine(location1.Name); // output: "entrance"
Console.WriteLine(world.Start.Name); // output: nothing
class World
{
public Location Start {get;set;}
public World (Location start) {Start = start;}
}
class Location
{
public string Name {get;set;}
public Location (); { }
public Location (string name) {Name = name;}
}
寻找一种更新实例的方法,以便正确更新所有引用。
In my task, I need to create a linked data structure between classes. A problem I faced is that when declaring references in another class and changing these references later outside the class, the previous class ignores the change. Example:
Location location1 = new Location(); // Name null
World world = new World(location1);
location1 = new Location("entrance"); // Name chosen
Console.WriteLine(location1.Name); // output: "entrance"
Console.WriteLine(world.Start.Name); // output: nothing
class World
{
public Location Start {get;set;}
public World (Location start) {Start = start;}
}
class Location
{
public string Name {get;set;}
public Location (); { }
public Location (string name) {Name = name;}
}
Looking for a way to update instances so that all references are correctly updated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
location1和world.start指向内存地址。但是,当上述行运行时,您告诉Location1指向设置新位置的其他内存地址。 World.Start仍指向上一个地址。
在这里,您实际上是在更新名称的值,而不是更改位置1点的位置。
https:///wwwwwww.tutorialsteacher.com/csharp/csharp/csharp-/csharp--csharp--csharp--价值型和参考类型
location1 and world.Start are pointing to a memory address. But when the above line is ran, you are telling location1 to point to a different memory address where the new Location is set. world.Start is still pointing to the previous address.
Here, you are actually updating the value of Name, rather than changing where location1 points to.
https://www.tutorialsteacher.com/csharp/csharp-value-type-and-reference-type