0

在下面的代码中,StylusPointCollection (SPC) 根据我是在方法内部还是外部声明 StylusPoint 变量而变化(即,如果我注释内部定义并取消注释注释行)。我不明白为什么会这样。

//StylusPoint spXY;

private void DrawBinaryTree(int depth, StylusPoint pt, double length, double theta)
{        
    if (depth > 0)
    {    
        StylusPoint spXY = new StylusPoint(pt.X + length * Math.Cos(theta) * Math.Cos(a), pt.Y + length * Math.Sin(theta) * Math.Sin(a));

        //spXY = new StylusPoint(pt.X + length * Math.Cos(theta) * Math.Cos(a), pt.Y + length * Math.Sin(theta) * Math.Sin(a));

        SPC.Add(pt);
        SPC.Add(spXY);

        DrawBinaryTree(depth - 1, spXY, length * lengthScale, theta + deltaTheta);
        DrawBinaryTree(depth - 1, spXY, length * lengthScale, theta - deltaTheta);
    }
}

我尝试过使用 LinqPad 想出一个更简单的示例,但未能成功。

4

1 回答 1

3

不同之处在于您对函数进行了两次递归调用,试图将有问题的变量传递给两者。当您在函数外部声明变量时,每次调用都会修改它DrawBinaryTree。当您将变量声明为本地时,每次调用DrawBinaryTree都会获取自己的变量副本,其他调用无法修改

与当地人:

private void DrawBinaryTree(int depth, StylusPoint pt, double length, double theta)
{        
    if (depth > 0)
    {    
        StylusPoint spXY = new StylusPoint(pt.X + length * Math.Cos(theta) * Math.Cos(a), pt.Y + length * Math.Sin(theta) * Math.Sin(a));

        SPC.Add(pt);
        SPC.Add(spXY);

        //spXY has the values you just set above 
        DrawBinaryTree(depth - 1, spXY, length * lengthScale, theta + deltaTheta);
        //since spXY is local, it still has the values you set above in this
        //call to the function (recursive calls have not modified it)
        DrawBinaryTree(depth - 1, spXY, length * lengthScale, theta - deltaTheta);
    }
}

具有全局性:

StylusPoint spXY;

private void DrawBinaryTree(int depth, StylusPoint pt, double length, double theta)
{        
    if (depth > 0)
    {    
        spXY = new StylusPoint(pt.X + length * Math.Cos(theta) * Math.Cos(a), pt.Y + length * Math.Sin(theta) * Math.Sin(a));

        SPC.Add(pt);
        SPC.Add(spXY);

        //spXY has the values you just set above 
        //(assuming there are no other functions running on other threads that modify it)
        DrawBinaryTree(depth - 1, spXY, length * lengthScale, theta + deltaTheta);
        //spXY now has the values from the last recursive call to DrawBinaryTree!
        DrawBinaryTree(depth - 1, spXY, length * lengthScale, theta - deltaTheta);
    }
}
于 2012-08-10T13:23:40.787 回答