在C#中转换为int的效果

Yan*_*met 0 c# casting reference

有人可以花点时间向我解释语言基础:

int foo = myObject.SomeList.Count;
for (int i = 0 ; i < foo ; i++)
{
  myObject.SomeList.Add(bar);
}
Run Code Online (Sandbox Code Playgroud)

进入无限循环,因为foo引用了一个不断增加的值.将第一行修改为:

int foo = (int)myObject.SomeList.Count;
Run Code Online (Sandbox Code Playgroud)

让它消失,不知何故foo一劳永逸地从参考变为价值.这可能是教科书但是,为什么会这样呢?

非常感谢

编辑:好的,正如帕特里克提到的那样,无限循环只发生在没有先前存储到foo时,演员阵容毫无意义,这是有道理的.这确实是我在调试时最初的想法.因此,当演员修理它时我很惊讶.实际发生的事情是,当被编辑的代码与执行的代码之间存在同步问题时,Visual Studio误以为我已经修复了它,这导致了错误的结论.

Pat*_*ald 8

我在我的系统上试过这个,无法复制你的问题.然而,我可以使用以下代码复制它,也许这就是你的意思:

// SomeList is not empty before the loop
for (int i = 0; i < myObject.SomeList.Count; i++)
{
    myObject.SomeList.Add(bar);
}
Run Code Online (Sandbox Code Playgroud)

在这种情况下,我们不会将Count存储在int中,所以每次添加到列表中时,我们都会将i + 1与Count + 1进行比较,因此无限循环.


Meh*_*ari 6

你确定吗?!!

int是一种值类型.这不应该发生.

Jon Skeet,过来帮忙!