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

違いは、問題の変数を両方に渡そうとする関数に対して 2 つの再帰呼び出しを行うという事実から生じます。関数の外で変数を宣言すると、 を呼び出すたびに変数が変更されますDrawBinaryTree。変数 local を宣言すると、 への各呼び出し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 に答える