gpt4 book ai didi

c# - 如何测试 C# ref 参数是否引用相同的项目

转载 作者:可可西里 更新时间:2023-11-01 09:09:06 27 4
gpt4 key购买 nike

在 C# 中给定一个具有以下签名的函数

public static void Foo(ref int x, ref int y)

如果函数是用

调用的
int A = 10;
Foo(ref A, ref A)

在函数 Foo 中是否可以测试 x 和 y 参数引用同一个变量?对 x 和 y 进行简单的等效测试是不够的,因为在两个不同变量具有相同值的情况下也是如此。

最佳答案

如果你愿意使用不安全的代码,你可以比较底层变量地址:

public static bool Foo(ref int a, ref int b)
{
unsafe
{
fixed (int* pa = &a, pb = &b)
{
// return true iff a and b are references to the same variable
return pa == pb;
}
}
}

(根据@Michael Graczyk 的评论,编辑以从方法签名中删除 unsafe。)

关于c# - 如何测试 C# ref 参数是否引用相同的项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11497095/

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