c# - 如何验证两个输出参数不指向同一个地址?

标签 c#

我创建了一个带 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/

相关文章:

c# - 将 Delphi 枚举类型转换为 C# 中的类似事物

C#如何解析没有键名的json数据?

c# - Lightinject - 检测到递归依赖

c# - 从以编程方式创建的按钮事件调用函数

c# - 将密码学 vb.net 转换为 c#

c# - 两次存储相同列表的内存使用,按不同标准排序?

c# - 为什么我们使用@Master类型?

c# - 使用 LINQ 替换循环是否明智?

c# - 在Azure函数中通过查询字符串调整图像大小

c# - 如何在mongodb中选择嵌套文档?