我创建了一个带 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
}
我知道解决这个问题的一种更简单的方法就是使用方法局部变量并且只在最后复制到输出参数,但我很好奇是否有一种简单的方法来验证地址,这样不需要。
最佳答案
我不确定您为什么想知道它,但这里有一个可能的 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();
}
最初我必须将两个变量都设置为任意值。然后将一个变量设置为不同的值:如果另一个变量也发生了变化,那么它们都指向同一个变量。
关于c# - 如何验证两个输出参数不指向同一个地址?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11786364/