我创建了一个带有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参数,但我很好奇是否有一种简单的方法可以验证地址这样不是必需的。
答案 0 :(得分:5)
我不确定你为什么想知道它,但这可能是黑客攻击:
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();
}
最初我必须将两个变量都设置为任何值。然后将一个变量设置为不同的值:如果另一个变量也被更改,则它们都指向同一个变量。