我创建了一个带 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 参数,但我很好奇是否有一种简单的方法来验证地址,这样就不需要这样做了.