简体   繁体   English

C#本地复制的变量值不断变化

[英]C# local copied variable value keep changing

I am facing this strange problem with strings. 我正在面对字符串这个奇怪的问题。

I assigned a string like this: 我分配了这样的字符串:

string temp = DateTime.UtcNow.ToString("s");
_snapShotTime = string.Copy(temp);

//here threads started....
//while thread progressing I am passing  _snapShotTime to create a directory.
//same in second threads.

But the time of local private variable _snapShotTime is keep on changing. 但是局部私有变量_snapShotTime的时间一直在变化。 I don't know why. 我不知道为什么 I have used a local variable and copy value in it. 我使用了局部变量并在其中复制了值。

Thanks 谢谢

I suspect your thread uses a lambda expression (or anonymous function) which captures _snapShotTime . 我怀疑您的线程使用捕获 _snapShotTime的lambda表达式(或匿名函数)。 That would indeed allow it to be changed. 这确实将允许对其进行更改。 It's hard to say for sure without any code though. 虽然没有任何代码,但很难确定。

If this is the problem, it's typically that you're referring to a captured variable which is declared outside the loop, but changed on every iteration of a loop. 如果这问题所在,通常是指在循环外部声明但在循环的每次迭代中都已更改的捕获变量。 You can fix this by declaring a new variable which takes a copy of the original variable inside the loop, and only using that copy variable in the lambda expression. 您可以通过声明一个新变量来解决此问题,该变量循环获取原始变量的副本,并且仅在lambda表达式中使用该副本变量。 You'll get a "new" variable inside the loop on each iteration, so you won't have problems. 每次迭代时,您都会在循环内获得一个“新”变量,因此不会出现问题。

Why don't you just do 你为什么不做

_snapShotTime = DateTime.UtcNow.ToString("s");

Also, place a breakpoint on that line and see when it is being called. 另外,在该行上放置一个断点,看看何时被调用。

When it does break, see the stack and it will clarify things. 当它确实中断时,请查看堆栈,它将进行澄清。

I suspect that your threads change the value of _snapShotTime 我怀疑您的线程更改了_snapShotTime的值

Strings are immutable, they do not change unless a variable is reassigned to a new string. 字符串是不可变的,除非将变量重新分配给新字符串,否则它们不会更改。

We need to see more code in order to help pinpoint the problem. 我们需要查看更多代码以帮助查明问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM