初学者:是否有一种优雅的方式来更新实例的所有副本?
以下代码不会更新数组内部的副本。
int a = null;
int[] numbers = new int[1];
numbers[0] = a;
a = 5; // 5
Console.WriteLine(numbers[0]); // null
获得了一个编程任务,需要设置由门户之间链接的位置结构,这仅通过列出所需的连接就不可能。即使我以后在代码中填写实体,我也会得到NULL的参考。
寻找可能解决我问题的关键字或技术。
The following code doesn't update the copy of a inside the array.
int a = null;
int[] numbers = new int[1];
numbers[0] = a;
a = 5; // 5
Console.WriteLine(numbers[0]); // null
Got a programming task requiring to set-up a structure of locations linked by portals between them which isn't possible by just listing the required connections. I'll get references to null that stay null even if I fill an entity later in the code.
Looking for keywords or techniques which might solve my issue.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以具有参考类型而不是数组中的值类型,因此更新内在对象的值也会影响数组。
You could have reference types instead of value types inside array, therefore updating the value of the inner object will also affect the array.
整数为a ,因此复制了实际值。因此,您的示例代码中从未有任何“实例”,只有该值的副本。
您可能应该将您的价值包裹在一堂课中,因为类是A 参考类型以获得所需的行为。当您需要在多个组件之间共享一些可变的时,这可能会很有用。您还可以添加一个事件,每当更改值以使需要值的任何组件都知道它可能需要更新某些内容时,该事件会添加。例如:
也有裁判返回和参考本地可以做类似您的示例的事情,但这主要是为了避免大型结构的副本来获得更好的性能,如果要在组件之间共享值,这将不那么有用。
integers is a value type, as such the actual value is copied. So there is never any 'instance' in your example code, only copies of the value.
You should probably wrap your value in a class, since classes are a reference type to get your desired behavior. This might be useful when you need to share some mutable between multiple components. You can also add an event that is raised whenever the value is changed to let any component that needs the value know that it might need to update something. For example:
There is also ref return and ref locals that could do something like your example, but this is mostly intended to get better performance by avoiding copies of large structs, it is not as useful if you want to share values between components.
数组是参考类型,
您只需要记住,您比您想要的要深度更深。这有点有些黑客,我可能会像其他答案一样为它上课,但是在大小1的数组中填充值类型可能是一种有用的技术,可以快速从价值类型中获得参考类型的行为
Arrays are reference types
You just have to remember that you're one level deeper than you wanted to be/you need to stick a
[0]
on everything you wouldn't have stuck it on before. It's a bit of a hack, and I'd probably make a class for it like other answers recommend, but stuffing a value type in an array of size 1 can be a useful technique to quickly get reference type behavior out of a value type当地人即使由于涉及对象的寿命而受到严格的限制,他们可能会帮助您完成任务。
基于您的问题的一个小示例可以如下:
这不仅可以使用价值类型(包括无效类型),还可以与参考类型一起使用。
ref
locals may help you in your task, even if they have strict limitations due to the lifetime of the involved objects, so they could be not applicable as a general solution.A small example based on your question can be as follows:
This works not only with value types (including nullable types) but also with reference types.