1

2 つのパラメーターを取り出すメソッドを作成しました。呼び出しコードで両方のパラメーターに同じ変数を渡すことができることに気付きましたが、この方法ではこれらのパラメーターを別々にする必要があります。これが真実であることを検証する最良の方法だと思う方法を思いつきましたが、それが 100% うまくいくかどうかはわかりません。これが私が思いついたコードで、質問が埋め込まれています。

private static void callTwoOuts()
{
    int same = 0;
    twoOuts(out same, out same);

    Console.WriteLine(same); // "2"
}

private static void twoOuts(out int one, out int two)
{
    unsafe
    {
        // Is the following line guaranteed atomic so that it will always work?
        // Or could the GC move 'same' to a different address between statements?
        fixed (int* oneAddr = &one, twoAddr = &two)
        {
            if (oneAddr == twoAddr)
            {
                throw new ArgumentException("one and two must be seperate variables!");
            }
        }

        // Does this help?
        GC.KeepAlive(one);
        GC.KeepAlive(two);
    }

    one = 1;
    two = 2;
    // Assume more complicated code the requires one/two be seperate
}

この問題を解決する簡単な方法は、単にメソッド ローカル変数を使用し、最後に out パラメーターにコピーするだけであることはわかっていますが、これが不要になるようにアドレスを検証する簡単な方法があるかどうかに興味があります。 .

4

1 に答える 1

5

I'm not sure why you ever would want to know it, but here's a possible hack:

private static void AreSameParameter(out int one, out int two)
{
    one = 1;
    two = 1;
    one = 2;
    if (two == 2)
        Console.WriteLine("Same");
    else
        Console.WriteLine("Different");
}

static void Main(string[] args)
{
    int a;
    int b;
    AreSameParameter(out a, out a); // Same
    AreSameParameter(out a, out b); // Different
    Console.ReadLine();
}

Initially I have to set both variables to any value. Then setting one variable to a different value: if the other variable was also changed, then they both point to the same variable.

于 2012-08-02T22:02:43.187 に答える