【发布时间】:2011-09-29 02:16:36
【问题描述】:
我有以下代码,当它运行时查看它显示初始的“myInt”和“myFloat”在方法调用返回之前不会改变它们的值。每次在被调用的方法中更改它们的值时,它们的值不应该改变吗,因为它们每次都作为“ref”传递?
class Tester
{
public void Run()
{
int myInt = 42;
float myFloat = 9.685f;
Console.WriteLine("Before starting: \n value of myInt: {0} \n value of myFloat: {1}", myInt, myFloat);
// pass the variables by reference
Multiply( ref myInt, ref myFloat );
Console.WriteLine("After finishing: \n value of myInt: {0} \n value of myFloat: {1}", myInt, myFloat);
}
private static void Multiply (ref int theInt, ref float theFloat)
{
theInt = theInt * 2;
theFloat = theFloat *2;
Divide( ref theInt, ref theFloat);
}
private static void Divide (ref int theInt, ref float theFloat)
{
theInt = theInt / 3;
theFloat = theFloat / 3;
Add(ref theInt, ref theFloat);
}
public static void Add(ref int theInt, ref float theFloat)
{
theInt = theInt + theInt;
theFloat = theFloat + theFloat;
}
static void Main()
{
Tester t = new Tester();
t.Run();
}
}
【问题讨论】:
-
您是否在调试器中查看它们的值?你在观察什么价值观?具体调用哪个方法?
-
我似乎找不到相关的 SO 问题,但我很确定这种情况(通过 ref 传递值,其中局部范围变量与 ref 参数具有相同的名称)混淆了调试器,它可能不会显示正确的值。它对代码执行没有影响,只是在调试时实时检查。
-
并且仅在图形调试器上 - 命令行应返回正确的
this.myInt值。 -
@sixlettervariables 是的,我正在调试器中将它们添加到我的监视列表中。一旦它进入第一个被调用的方法,它们就会变得模糊/变灰,但它们的值(以及它们的变灰/模糊状态)在调用堆栈返回到 Run() 方法之前不会改变。
-
此外,如果您正在备份调用堆栈以从命令行查看值,它也不会是最新的,因为您在执行此操作时已经及时返回。作为@Fernaref,这只会影响在当前断点处使用 GUI 在活动过程之外进行检查。
标签: c# .net pass-by-reference value-type