始终保存当前变量值的列表。 C#
因此,我需要一个列表(或类似的数据结构),在添加给定变量后始终保存该变量的当前值。这就是当前发生的情况(在更简单/伪代码中):
intValue = 5;
intList.Add(intValue);
Print intList[0].toString();
打印“5”
intValue++;
Print intList[0].toString();
当我希望它打印 intValue 的新值“6”时,仍然打印“5”。
基本上,列表需要存储对 intValue 的引用(我认为这是正确的术语),而不是它的实际值。感谢您抽出时间。
So I need a list (or similar data structure) that always holds the current value for a given variable, once it has been added. This is what currently occurs (in simpler/pseudo code):
intValue = 5;
intList.Add(intValue);
Print intList[0].toString();
Prints "5"
intValue++;
Print intList[0].toString();
Still Prints "5" when I want it to print intValue's new value, "6".
Basically the list needs to store a reference to intValue (I think that's the correct terminology) and not it's actual value. Thanks for your time.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您的问题与以下内容非常相似:
How to get a list of mutable字符串?
更改接受答案中的
SortOfMutableString
实现以存储int
值而不是string
,您将获得所需的效果。另外,请查看 Jon Skeet 的回答。这对于充分理解此类解决方案的后果非常重要。
Your question is pretty similar to the following:
How to get a list of mutable strings?
Change the
SortOfMutableString
implementation in the accepted answer to storeint
values instead ofstring
and you'll get the desired effect.Also, check out Jon Skeet's answer there. This is very important to fully understand the consequences of such kind of solutions.
它不能通过更改列表类型来完成。您可能必须创建自己的引用类型,其行为类似于
int
。在 .net 中,结构不是引用类型,因此它们不可能获得您需要的行为。您必须意识到添加到列表中的
int
只是副本,因此对源代码所做的任何更改都不会影响副本。Its not something that could be done with changing type of the list. You might have to create your own reference type which will behave like
int
. In.net
structures are't reference types so its impossible with them to get such behaviour like you need.You have to realize that
int
you've added to your list is just copy, so any change done to source won't affect the copy.这是因为在 C# 中,
int
是值类型,而不是引用类型。当您编写时,您将副本添加到
intValue
,而不是对变量本身的引用。您想要的是将变量intValue
的引用添加到intList
中。您可以做的是将您的int
值包装在您自己的类中(这是一个引用类型)。This is because in C#,
int
is a value type instead of reference type. When you writeyou add a copy to
intValue
, and not a reference to the variable itself. What you want is to add a reference to the variableintValue
tointList
. What you can do is wrap yourint
values in a class of you own (which is a reference type).由于您需要存储引用而不是变量的值,因此可以存储指针。您需要使用
unsafe
关键字才能在 C# 中使用指针。Since you will need to store the reference instead of the value of the variables, you can store the pointers. You will need to use
unsafe
keyword to use pointers in C#.