初学者:如何在多个类中正确更新引用?

发布于 2025-01-26 14:58:53 字数 606 浏览 2 评论 0原文

在我的任务中,我需要在类之间创建一个链接的数据结构。我遇到的一个问题是,当在同类课堂外宣布参考并更改这些引用时,上一类忽略了更改。示例:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

阳光①夏 2025-02-02 14:58:53
location1 = new Location("entrance");

location1和world.start指向内存地址。但是,当上述行运行时,您告诉Location1指向设置新位置的其他内存地址。 World.Start仍指向上一个地址。

Location location1 = new Location(); // Name null
World world = new World(location1);
location1.Name = "entrance"; // Name chosen

在这里,您实际上是在更新名称的值,而不是更改位置1点的位置。

https:///wwwwwww.tutorialsteacher.com/csharp/csharp/csharp-/csharp--csharp--csharp--价值型和参考类型

location1 = new Location("entrance");

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.

Location location1 = new Location(); // Name null
World world = new World(location1);
location1.Name = "entrance"; // Name chosen

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文