gpt4 book ai didi

c# - 在运行时测试传入的 ByRef 参数是否与给定的 "other"变量共享存储位置

转载 作者:行者123 更新时间:2023-11-30 22:16:26 25 4
gpt4 key购买 nike

这个问题更多是出于好奇而不是出于实际需要。

有什么方法可以测试传递给 ByRef(即 C# 中的 refout)的参数是否有与某些“其他”变量相同的存储位置?我并不是要测试对象是否相同,因为两个不同的引用变量可能是对同一对象的两个不同引用。

我想出了一些例子来解释我的意思。考虑:

public static void SillySwap(ref int a, ref int b)
{
// first put sum of original numbers into slot a,
// then use that to get out the original numbers swapped
a = a + b;
b = a - b;
a = a - b;
}

(我们通常会使用第三个临时变量来代替,但为了说明我的问题,我是这样做的。)SillySwap 如果你使用两个变量就可以正常工作, 数值相同或不同。但是如果你这样调用它:

int shared = 42;
SillySwap(ref shared, ref shared);

它将消灭shared如果 ab 作为存储位置相等,我是否可以在 SillySwap 的主体内进行测试?

这是一个带有字段(“类变量”)的修改示例:

protected static int field;
public static void SillySwap2(ref int arg)
{
arg = arg + field;
field = arg - field;
arg = arg - field;
}

这里我们要检查传入的arg是否真的是变量field

最后一个例子,考虑这个:

static bool SillyTryGetStrings(out string first, out string second)
{
// the order of assignment may matter here!
second = "world";
first = "Hello";

return true;
}

假设一些陌生人为 firstsecond 传入相同的变量。我们可以在方法内部检查吗?

最佳答案

一种方法是使用不安全代码并比较指向变量的指针:

public unsafe bool AreRefsEqual(ref int a, ref int b)
{
fixed (int* aptr = &a)
fixed (int* bptr = &b)
{
return aptr == bptr;
}
}

[TestMethod]
public void ShouldRefsEqualWork()
{
int a = 1, b = 1;
Assert.IsTrue(AreRefsEqual(ref a, ref a));
Assert.IsFalse(AreRefsEqual(ref a, ref b));
}

关于c# - 在运行时测试传入的 ByRef 参数是否与给定的 "other"变量共享存储位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17389346/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com